2014-10-19 33 views
1

我正在編譯我的Python腳本到Windows可執行文件。該腳本只需下載一個文件並將其保存在本地 - 每次下載都使用不同的線程。我發現我的簡單應用程序在任何線程完成之前退出。但我不完全確定?使exe繼續直到完成一個線程

在線程結束之前我的腳本是否退出或腳本是否等待完成? AND如果腳本在線程完成之前退出 - 我該如何阻止?

什麼他們標準的做法,以避免這種情況?我應該使用一個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 – 2014-10-19 22:56:32

+0

@JakeM,我同意這個答案。你也可以嘗試'threads = threading.enumerate()',然後檢查線程是否存在。我遇到了懸掛流程的相反情況。我做了這個檢查,我懷疑有一些線程仍在執行,這阻止了我的主進程退出。我開始明白,如果一個線程仍然在做某件事情,那麼即使主線程退出,主進程也不會結束。 – ksrini 2014-10-30 15:10:20

相關問題