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")
感謝這很好的解釋,加上一個簡單的解決方案對我來說:D – 2014-10-19 22:56:32
@JakeM,我同意這個答案。你也可以嘗試'threads = threading.enumerate()',然後檢查線程是否存在。我遇到了懸掛流程的相反情況。我做了這個檢查,我懷疑有一些線程仍在執行,這阻止了我的主進程退出。我開始明白,如果一個線程仍然在做某件事情,那麼即使主線程退出,主進程也不會結束。 – ksrini 2014-10-30 15:10:20