在后台python中作为线程运行函数并在其应用程序之前退出

Sum*_*wal 3 python multithreading

我在 python 中作为线程执行一个函数。现在,程序将等待函数执行,然后在完成后终止。

我的目标是启动后台线程并关闭调用它的程序。我们怎么做。如下面的代码,线程将需要 30 分钟来执行。我想在调用线程后停止主程序,让线程在后台运行。

thread = threading.Thread(target=function_that_runs_for_30_min)
thread.start()
print "Thread Started"
quit()
Run Code Online (Sandbox Code Playgroud)

Ser*_*sta 6

你不能直接这样做。线程只是进程的一部分。一旦进程退出,所有线程都消失了。您需要创建一个后台进程来实现这一点。

您不能使用该multiprocessing模块,因为它是一个支持使用类似于线程模块的 API 生成进程的包(强调我的)。因此,它没有规定允许进程在调用结束后运行。

我能想象的唯一方法是使用 subprocess 模块以特定参数重新启动脚本。对于简单的用例,添加一个参数就足够了,对于更复杂的命令行参数,argparse应该使用模块。代码示例:

import subprocess
import sys

# only to wait some time...
import time

def f(name):
    "Function that could run in background for a long time (30')"
    time.sleep(5)
    print 'hello', name

if __name__ == '__main__':
    if (len(sys.argv) > 1) and (sys.argv[1] == 'SUB'):
        # Should be an internal execution: start the lengthy function
        f('bar')
    else:
        # normal execution: start a subprocess with same script to launch the function
        p = subprocess.Popen("%s %s SUB" % (sys.executable, sys.argv[0]))
        # other processing...
        print 'END of normal process'
Run Code Online (Sandbox Code Playgroud)

执行:

C:\>python foo.py
END of normal process

C:\>
Run Code Online (Sandbox Code Playgroud)

五秒后:

hello bar
Run Code Online (Sandbox Code Playgroud)