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