Python run system command and then exit… won't exit

拟墨画扇 提交于 2019-12-20 10:40:56

问题


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?


回答1:


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



回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/6807102/python-run-system-command-and-then-exit-wont-exit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!