2014-09-30 52 views
0

因此,我已經做了一個程序,自動更新人民框,我有這一切工作,然後我回去,並使其多線程,一切工作時,我硬編碼線程在我的自我中,現在我想爲從文件中讀入的每個用戶創建一個新線程,我不知道如何爲我的程序執行此操作。我的程序的其餘部分完成後只需動態地創建線程。我的代碼在下面,我評論了我認爲線程應該開始的位置。動態在python中爲每個用戶從文本文件中讀取線程

def run(self) 
    try: 
    location = "location" 
    onloc = "onloc" 
    port = 22 
    self.Put(location, onloc, self.ThreadIP, self.ThreadPw, self.ThreadUser, port) 
    re = self.HTTPing("https://%s" %self.ThreadIP) 
    while not re: 
      time.sleep(60) 
      self.HTTPing("https://%s" %self.ThreadIP) 
      print "Is on" 
    except: 
     print ("This ip does not est %s" %self.ThreadIP) 


with open("People.txt" , 'r') as inFile:       
    for line in inFile: 
     ip,user,password = line.strip().split(',') 
     ""what should i put here to make threads 
+1

'MyThreadClass(arguments,go,here).start()'? – Kevin 2014-09-30 13:17:40

+0

你只需要創建你的線程類的實例,傳遞正確的參數。您也可以將這些實例存儲在某種數據結構中。 – tijko 2014-09-30 13:18:28

回答

0

我絕不是專家,但我做了這樣的事情對於一個小項目動態線程。我花了大約4個小時來創建,從那以後就沒有用過它!

thread.py:

def threadcode(): 
    do_stuff = True 

master.py:

from thread import threadcode as thread1 
from thread import threadcode as thread2 
from thread import threadcode as thread3 
from thread import threadcode as thread4 
# add more as required, or create dynamically 
threadstostart = ['thread1','thread2','thread3','thread4'] 
# list of threads to start can be created dynamically as per the imports  

while True: 
    #get missing threads 
    threadsrunning = [] 
    for name in threading.enumerate():  #for each thread running 
     threadname = str(name)    #convert thread object reference to string 
     if "MainThread" in threadname:  #exclude main thread 
      continue 
     i = threadname.find("(") + 1  #extract thread name 
     j = threadname.find(",")   #this will need to change if Python changes format 
     threadname = threadname[i:j]   
     threadsrunning.append(threadname) #add running thread to list 

    threadsnotrunning = list(set(threadstostart) - set(threadsrunning)) #calculate list of threads not running 

    for threadname in threadsnotrunning: 
     threadtostart = globals()[threadname]       # set missing thread 
     thread = threading.Thread(name=threadname,target=threadtostart) # set threading object 
     thread.start()             # start thread 

    sleep(10) #do nothing for a bit 

可以創建這樣你的狀態

""what should i put here to make threads 

,並建立起自己的 「threadstostart」 列表中的進口,並立即運行我上面使用的線程啓動器代碼。你仍然需要傳遞你的參數來確定每個線程與什麼相關...