Sunday, December 22, 2013

Python Threading - An Intro from my learning

This is my first attempt at utilizing threading within a python script.  I've kept it simple so that others can use it as an example while they tackle the process of learning some of these more advanced concepts of python.  Comments and feedback are appreciated.

The first step involves importing the "treading" module.  Next, you'll need to use threading.Thread(target=<your code/function call>).  The last step will be to begin your threads with the start() method.  First get your code running without using threading, then modifying it to be used with threading.  Hope this helps someone.

#!/usr/bin/python

# Import the necessary modules
import threading
import ftplib

# FTP function - Connects and performs directory listing
def ftpconnect(target):
        ftp = ftplib.FTP(target)
        ftp.login()
        print "File list from: %s" % target
        files = ftp.dir()
        print files

# Main function - Iterates through a lists of FTP sites creating theads
def main():
sites = ["ftp.openbsd.org","ftp.ucsb.edu","ubuntu.osuosl.org"]
for i in sites:
myThread = threading.Thread(target=ftpconnect(i))
myThread.start()
print "The thread's ID is : " + str(myThread.ident)
if (__name__ == "__main__"):
main()

No comments:

Post a Comment