0

I want to run a shell script in background with the subprocess. However, I don't want to wait for it to complete. I want it to run in background and terminate after it finishes. For simplicity, I am using the sleep command as my script. But as soon as I run, it terminates. If I put the communicate or wait method, then it keeps running but this is not what I want.

def run():
    subprocess.Popen(["sleep", "25s"])
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
ravi
  • 133
  • 12

1 Answers1

0

Have you looked at what happens when you run your program? Even though it seems like the program ends, the thread will contiune to execute to completion. In your current example, this is hard to see but looking at an example like

import threading

def wait_print():
    time.sleep(5)
    print('delayed')

t = threading.Thread(target=wait_print)
t.start()

If you store this program as e.g. delayed_print.py and the runs python delayed_print.py from the command line, you will see that the program ends and control is returned to the shell, but then a few seconds later, the text delayes is suddenly appearing in the shell window.

JohanL
  • 6,671
  • 1
  • 12
  • 26