la6470
la6470

Reputation: 29

python daemon thread is exiting when process is killed

I am starting a python script on one terminal and then from another terminal issuing a kill -9 to kill the process. I am hoping that even when the parent process is killed the thread will continue to execute and touch the file. But that is not happening. Any clue how I can achieve this?

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()

Upvotes: 0

Views: 698

Answers (1)

dano
dano

Reputation: 94881

What you are trying is impossible, unfortunately. Threads can only run as long as their parent process runs. If you want to start executing some code from your script, but have that code continue executing after your script exits, you should move that code into a separate script and use the subprocess module to launch it. Specifically, you can use subprocess.Popen to launch the script without blocking to wait for it to complete:

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

Upvotes: 1

Related Questions