使Exe继续直到线程已完成

时间:2014-10-19 01:59:11

标签: python multithreading concurrency

我正在将我的Python脚本编译成Windows可执行文件。该脚本只需下载一个文件并将其保存在本地 - 每次下载都使用不同的线程。我发现我的简单应用程序在任何线程完成之前退出。但我不完全确定吗?

我的脚本是否在线程完成之前退出,或脚本是否等到完成之后? 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")   

1 个答案:

答案 0 :(得分: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")  
相关问题