【问题标题】:python daemon thread is exiting when process is killed进程被杀死时python守护程序线程正在退出
【发布时间】:2014-07-19 04:04:52
【问题描述】:

我在一个终端上启动一个 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()

【问题讨论】:

    标签: python multithreading daemon


    【解决方案1】:

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

    subprocess.Popen(['./yourscript.py', '-a', 'opt'])
    

    【讨论】:

      猜你喜欢
      • 2013-04-29
      • 1970-01-01
      • 2019-05-01
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多