I'm trying to multithread my Python application. This is how i thought the application would work:
- A list of ipv4 addresses is created by the user
- For each ipv4 address, the application establishes an SSH connection and logs in. This part would benefit from multithreading since each device takes about 10 seconds to complete. The ssh bit is all handled by my ConfDumper class.
- in each thread, a bit of data is fetched from the network device and should be returned to the main thread (where there is a list of devices)
- Once all threads are done, a result is presented.
Being new to Python and having no experience with multithreading, I've tried something like this:
import threading
import confDumper
class MyThread (threading.Thread):
device = None
# A device object is sent as agument
def __init__(self, device):
threading.Thread.__init__(self)
self.device = device
def run(self):
print "Starting scan..."
self.sshscan()
print "Exiting thread"
def sshscan(self):
s = confDumper.ConfDumper(self.device.mgmt_ip, self.device.username, self.device.password, self.device.enable_password)
t = s.getConf()
if t:
# We got the conf, return it to the main thread, somehow...
It seems to be working when I debug the code and step though the lines one by one, but once the thread is closed all results from the thread are lost. How do I return the result to the main thread?
devicewhen you in fact mean them to be instance-attributes. It's not how Python does it, and it will bite you in the future if you happen to make it a mutable thing instead of None.device = Noneat class-level. Instance-attributes should be declared at__init__, you actually can create them at any method/time - but it's considered bad style & will be flagged by any self-respecting linter.