我有两个python文件:
a.py:
import subprocess, time, os, signal
myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.SIGTERM)b.py:
import atexit
def cleanup():
print "Cleaning up things before the program exits..."
atexit.register(cleanup)
print "Hello world!"
while True:
passa.py正在繁殖b.py,2秒后它就会杀死这个过程。问题是,我希望cleanup函数在它被杀死之前调用b.py,但我无法让它工作。
我还在SIGKILL函数中尝试了os.kill和SIGINT,但这两种方法都不适合我。
电流输出(a.py):
Hello, World!
(2 seconds later, program ends)预期输出(a.py):
Hello, World!
(2 seconds later)
Cleaning up things before the program exits...
(program ends)发布于 2018-02-10 16:23:52
对Windows使用不同的信号:signal.CTRL_C_EVENT
在a.py中多睡一会儿,否则子进程在父进程退出之前没有机会清理:
import subprocess, time, os, signal
myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.CTRL_C_EVENT)
time.sleep(2)如果您实际上不需要shell特性,那么我还想劝阻您不要使用shell:
import subprocess, time, os, signal, sys
myprocess = subprocess.Popen([sys.executable, "b.py"])Linux/macOS用户:signal.CTRL_C_EVENT不存在,您需要signal.SIGINT。
https://stackoverflow.com/questions/48722824
复制相似问题