2014-10-19 2 views
1

파이썬 스크립트를 Windows 실행 파일로 컴파일 중입니다. 이 스크립트는 단순히 파일을 다운로드하고 로컬에 저장합니다. 각 다운로드마다 다른 스레드가 사용됩니다. 스레드가 완료되기 전에 간단한 응용 프로그램이 종료된다는 것을 알았습니다. 그러나 나는 완전히 확신하지 못하는가?스레드가 완료 될 때까지 EXE 계속하기

스레드가 끝나기 전에 내 스크립트가 종료되거나 스크립트가 완료 될 때까지 기다리지 않습니까? 스레드가 완료되기 전에 스크립트가 종료되면 어떻게합니까?

이것을 피하기 위해 표준 연습은 무엇입니까? 스레드가 아직 살아 있는지 또는이를 수행하는 표준 방법이 있는지 검사하는 while 루프를 사용해야합니까?

import thread 
import threading 
import urllib2 

def download_file(): 

    response = urllib2.urlopen("http://website.com/file.f") 
    print "Res: " + str(response.read()) 
    raw_input("Press any key to exit...") 

def main(): 

    # create thread and run 
    #thread.start_new_thread (run_thread, tuple()) 

    t = threading.Thread(target=download_file) 
    t.start() 


if __name__ == "__main__": 
    main() 
    # The below prints before "Res: ..." which makes me think the script exits before the thread has completed 
    print("script exit") 

답변

2

새로 만든 스레드에서 join() 함수를 사용하면 스레드가 완료 될 때까지 코드 실행이 차단됩니다. 나는 여기에 완전히 필요하지 않고 단지 혼란을 일으키기 때문에 def main()을 제거하는 자유를 취했다. 모든 다운로드의 시작을 깔끔한 함수로 바꾸려면 설명적인 이름을 선택하십시오. 이이었다

import thread 
import threading 
import urllib2 
def download_file(): 
    response = urllib2.urlopen("http://website.com/file.f") 
    print "Res: " + str(response.read()) 
    raw_input("Press any key to exit...") 

if __name__ == "__main__": 
    t = threading.Thread(target=download_file) 
    t.start() 
    t.join() 
    # The below prints before "Res: ..." which makes me think the script exits before the thread has completed 
    print("script exit") 
+0

덕분에 잘 설명, 플러스 나를 위해 쉬운 솔루션 : D –

+0

@JakeM, 나는이 답변에 동의합니다. 또한'threads = threading.enumerate()'를 시도한 다음 스레드가 살아 있는지 확인할 수 있습니다. 나는 교수형을당하는 과정과 정반대의 상황을 겪었다. 내 주 프로세스가 종료되지 못하게하는 스레드가 여전히 실행 중이라고 의심되는 경우에 해당 검사를 수행했습니다. 스레드가 여전히 무언가를하고 있다면 주 프로세스가 종료 되더라도 종료되지 않는다는 것을 이해하게되었습니다. – ksrini

관련 문제