13

I tried these two methods:

os.system("python test.py")

subprocess.Popen("python test.py", shell=True)

Both approaches need to wait until test.py finishes which blocks main process. I know "nohup" can do the job. Is there a Python way to launch test.py or any other shell scripts and leave it running in background?

Suppose test.py is like this:

for i in range(0, 1000000):
    print i

Both os.system() or subprocess.Popen() will block main program until 1000000 lines of output displayed. What I want is let test.py runs silently and display main program output only. Main program may quie while test.py is still running.

0
37

subprocess.Popen(["python", "test.py"]) should work.

Note that the job might still die when your main script exits. In this case, try subprocess.Popen(["nohup", "python", "test.py"])

12
  • 1
    subprocess.Popen(["python", "test.py"]) just launches test.py and blocks main process by waiting for the output of test.py. – jack Oct 22 '09 at 7:30
  • 2
    That should only happen if you request stdout=PIPE as well. Which version of Python? Can you add a print "xxx" after the call to Popen to check that it really blocks? – Aaron Digulla Oct 22 '09 at 8:30
  • I just tested the code above and it works for me with Python 2.5.2 on Windows. Your problem must be something else. – Aaron Digulla Oct 22 '09 at 8:33
  • i tried again and it worked. sorry about the mistake and thanks for your answer. – jack Oct 22 '09 at 8:51
  • 1
    @AaronDigulla: Is there no way to simply launch script in seperate process without blocking the main process ? – igor Nov 20 '15 at 10:07
1
os.spawnlp(os.P_NOWAIT, "path_to_test.py", "test.py")
5
  • it works, but is it possible to let test.py runs silently? – jack Oct 22 '09 at 8:29
  • silently? do you mean you don't want to see the output on screen? – Vissu Oct 22 '09 at 8:32
  • yes, i dont want to see the output on screen. can i be done by adding ">> /dev/null" to the code? – jack Oct 22 '09 at 8:39
  • Unfortunately I think os.spawn*() doesn't support output redirection! – Vissu Oct 22 '09 at 8:51
  • 8
    os.spawn* have been deprecated by the subprocess module. – habnabit Oct 22 '09 at 20:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.