在python中为从文本文件读入的每个用户动态创建线程

时间:2014-09-30 13:13:27

标签: python multithreading

所以我已经制作了一个自动更新人物盒子的程序,我把它全部工作然后我回去使它成为多线程,当我在我自己的硬编码线程时,一切正常,现在我想创建一个新线程每个用户都从文件中读入,我不知道如何为我的程序执行此操作。我的程序的其余部分只需要动态制作线程。我的代码在下面,我评论我认为线程应该从哪里开始。

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 个答案:

答案 0 :(得分: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”列表,并立即运行我上面使用的线程启动码。你仍然需要传入你的参数来确定每个线程与...相关的内容......