当进程被终止时,python守护进程线程正在退出

时间:2014-07-18 20:03:03

标签: python multithreading daemon

我在一个终端上启动python脚本,然后从另一个终端发出kill -9来杀死进程。我希望即使父进程被杀死,线程仍将继续执行并触摸该文件。但那并没有发生。有什么线索我能做到这一点吗?

import time,os
import threading
# Create your tests here.

def a(fname):
    print "a"
    time.sleep(20)
        touch(fname)

def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)
    print "touched"

fname = "test.txt"
t = threading.Thread(target=a, args=(fname,))
t.setDaemon(True)
t.start()
t.join()

1 个答案:

答案 0 :(得分:1)

不幸的是,你正在尝试的是不可能的。只有父进程运行时,线程才能运行。如果要从脚本开始执行某些代码,但在脚本退出后继续执行该代码,则应将该代码移动到单独的脚本中并使用subprocess模块启动它。具体来说,您可以使用subprocess.Popen启动脚本而不会阻止它等待它完成:

subprocess.Popen(['./yourscript.py', '-a', 'opt'])
相关问题