为从文本文件读入的每个用户动态生成python线程
所以我制作了一个自动更新People boxs的程序,我让它全部正常工作,然后我回去让它多线程,当我自己硬编码线程时一切都正常,现在我想为每个从文件中读取的用户创建一个新线程,我不知道如何为我的程序做到这一点。我的程序的其余部分已经完成,只需要动态生成线程。下面是我的代码,我评论了我认为线程应该从哪里开始为从文本文件读入的每个用户动态生成python线程,python,multithreading,Python,Multithreading,所以我制作了一个自动更新People boxs的程序,我让它全部正常工作,然后我回去让它多线程,当我自己硬编码线程时一切都正常,现在我想为每个从文件中读取的用户创建一个新线程,我不知道如何为我的程序做到这一点。我的程序的其余部分已经完成,只需要动态生成线程。下面是我的代码,我评论了我认为线程应该从哪里开始 def run(self) try: location = "location" onloc = "onloc" port = 22 self.P
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
我决不是一个专家,但我为一个小项目的动态线程做了类似的事情。我花了大约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列表,并立即运行我上面使用的线程启动程序代码。您仍然需要传入参数以确定每个线程与什么相关…MyThreadClassarguments,转到这里。开始?您只需要创建线程类的实例,传入正确的参数。您可能还希望将这些实例存储在某种数据结构中。