Python atexit处理程序不响应信号
我有两个python文件: a.py:Python atexit处理程序不响应信号,python,windows,signals,interrupt,kill,Python,Windows,Signals,Interrupt,Kill,我有两个python文件: a.py: import subprocess, time, os, signal myprocess = subprocess.Popen("b.py", shell=True) time.sleep(2) os.kill(myprocess.pid, signal.SIGTERM) import atexit def cleanup(): print "Cleaning up things before the program exits..."
import subprocess, time, os, signal
myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.SIGTERM)
import atexit
def cleanup():
print "Cleaning up things before the program exits..."
atexit.register(cleanup)
print "Hello world!"
while True:
pass
Hello, World!
(2 seconds later, program ends)
Hello, World!
(2 seconds later)
Cleaning up things before the program exits...
(program ends)
b.py:
import subprocess, time, os, signal
myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.SIGTERM)
import atexit
def cleanup():
print "Cleaning up things before the program exits..."
atexit.register(cleanup)
print "Hello world!"
while True:
pass
Hello, World!
(2 seconds later, program ends)
Hello, World!
(2 seconds later)
Cleaning up things before the program exits...
(program ends)
a.py
正在生成b.py
并在2秒后终止进程。问题是我希望cleanup
函数在它被杀死之前调用b.py
,但我无法让它工作
我还在os.kill
函数中尝试了SIGKILL
和SIGINT
,但这两种方法都不适用于我
电流输出(a.py):
import subprocess, time, os, signal
myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.SIGTERM)
import atexit
def cleanup():
print "Cleaning up things before the program exits..."
atexit.register(cleanup)
print "Hello world!"
while True:
pass
Hello, World!
(2 seconds later, program ends)
Hello, World!
(2 seconds later)
Cleaning up things before the program exits...
(program ends)
预期产量(平均值):
import subprocess, time, os, signal
myprocess = subprocess.Popen("b.py", shell=True)
time.sleep(2)
os.kill(myprocess.pid, signal.SIGTERM)
import atexit
def cleanup():
print "Cleaning up things before the program exits..."
atexit.register(cleanup)
print "Hello world!"
while True:
pass
Hello, World!
(2 seconds later, program ends)
Hello, World!
(2 seconds later)
Cleaning up things before the program exits...
(program ends)
对Windows平台使用不同的信号:
signal.CTRL\u C\u事件
在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\u C\u事件
不存在,您需要signal.SIGINT
你在什么平台上?Windows,但将来也可能是Linux。我明白为什么这是有意义的,但它仍然不起作用。。。你自己测试过吗?它对你有用吗?是的,我自己测试过,它在macOS上有效。我没有可用的windows框。实际上,您可以尝试使用signal.CTRL\u C\u EVENT
或signal.CTRL\u BREAK\u EVENT
?这东西非常依赖于平台,信号在Windows上有不同的可用性。这很有效!您知道signal.CTRL\u C\u EVENT
是否在linux上工作吗?非常感谢!:)没有(它甚至在Linux上都不存在)<代码>信号。CTRL\u C\u事件仅适用于Windows。