[英]Why child process (daemon=True) not exiting when main process exit in python?
[英]python daemon thread is exiting when process is killed
我正在一個終端上啟動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()
不幸的是,您正在嘗試的事情是不可能的。 線程只能在其父進程運行時運行。 如果要開始執行腳本中的某些代碼,但要在腳本退出后繼續執行該代碼,則應將該代碼移到單獨的腳本中,並使用subprocess
模塊啟動它。 具體來說,您可以使用subprocess.Popen
啟動腳本,而不會阻塞等待腳本完成:
subprocess.Popen(['./yourscript.py', '-a', 'opt'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.