12

I have the following python code:

os.system("C:/Python27/python.exe C:/GUI/TestGUI.py")
sys.exit(0)

It runs the command fine, and a window pops up. However, it doesn't exit the first script. It just stays there, and I eventually have to force kill the process. No errors are produced. What's going on?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • 3
    the problem is that the `os.system(command)` function blocks until the command is finished running, what the OP wants is to run the command without waiting for it to finish. – Dan D. Jul 24 '11 at 13:46
  • @Dan Exactly! I just realised that's the problem. Since the python script is running, it's still alive in the "shell", and os.system has to wait until the shell has been exited. How would I do this? –  Jul 24 '11 at 13:48
  • [subprocess](http://www.google.de/url?sa=t&source=web&cd=1&ved=0CBwQFjAA&url=http%3A%2F%2Fdocs.python.org%2Flibrary%2Fsubprocess.html&ei=3SIsTo-OCI7KtAarx8TVCw&usg=AFQjCNFdC9kYg-WOjimGNxIC3jQDKuai7A) should work, but docs.python.org seems to be down ... [here](http://cmpt165.csil.sfu.ca/Python-Docs/library/subprocess.html) is a mirror. – Jacob Jul 24 '11 at 13:49

4 Answers4

22

instead of os.system use subprocess.Popen

this runs a command and doesn't wait for it and then exits:

import subprocess
import sys

subprocess.Popen(["mupdf", "/home/dan/Desktop/Sieve-JFP.pdf"])
sys.exit(0)

note that os.system(command) like:

p = subprocess.Popen(command)
p.wait()
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • And if you are running your topmost script from inside a terminal window, you may experience this window to stick open even after you've exited your script and the `cmd.exe` itself!.. I've noticed this happening if you started some background processes from inside this window. Window does close after these processes exit. – spacediver Jul 24 '11 at 14:58
1

KeyboardInterrupts and signals are only seen by the process (ie the main thread). If your nested command hangs due to some kind of file read or write block, you won't be able to quit the program using any keyboard commands.

Why does a read-only open of a named pipe block?

If you can't eliminate the source of the disk block, then one way is to wrap the process in the thread so you can force kill it. But if you do this, you leave opportunity for half-written and corrupted files on disk.

Community
  • 1
  • 1
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
0

I suggest using os._exit instead of sys.exit, as sys.exit doesnt quit a program but raises exception level, or exits a thread. os._exit(-1) quits the entire program

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
0
import sys ,subprocess

subprocess.Popen(["C:/Python27/python.exe", "C:/GUI/TestGUI.py"])
sys.exit(0)

Popen from subprocess module what you are looking for.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
utdemir
  • 26,532
  • 10
  • 62
  • 81