2014-09-30 53 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” 列表中的进口,并立即运行我上面使用的线程启动器代码。你仍然需要传递你的参数来确定每个线程与什么相关...