2014-09-30 1 views
0

그래서 사람들이 자동으로 업데이트하는 프로그램을 만들었습니다. 모든 작업을 마치고 돌아가서 멀티 스레드로 만들었습니다. 스레드가 하드 코드 할 때 모든 것이 작동합니다. 내 스스로, 지금은 파일에서 모든 사용자가 읽을 수있는 새로운 스레드를 만들고 싶어, 나는 내 프로그램에 이것을 어떻게 해야할지 모르겠다. 나머지 프로그램은 스레드를 동적으로 만들 필요가 있습니다. 내 코드는 아래에있다, 나는 스레드가 시작되어야한다고 생각하는 곳에 주석을 달았다.동적으로 스레드를 만들어서 각 사용자가 파이썬에서 텍스트 파일을 읽음

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

+0

적절한 인수를 전달하여 스레드 클래스의 인스턴스를 만들어야합니다. 이러한 인스턴스를 일종의 데이터 구조 안에 저장할 수도 있습니다. – tijko

답변

0

저는 전문가는 아니지만 작은 프로젝트의 경우 동적 스레딩을 수행했습니다. 생성하는데 약 4 시간이 걸렸고, 그 이후로 사용하지 않았습니다!

thread.py :

def threadcode(): 
    do_stuff = True 

master.py : 당신은 당신이

""what should i put here to make threads 

를 명시하고 "threadstostart"목록을 구축 수입을 만들 수 있습니다

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 

, 위에 사용 된 스레드 시작 코드를 즉시 실행하십시오. 각 스레드와 관련이 있는지 확인하기 위해 인수를 전달해야합니다 ...

관련 문제