atexit 处理程序不响应信号

atexit handler not responding to signals

我有两个 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:
    pass

a.py 正在生成 b.py 并且在 2 秒后它正在终止进程。问题是我希望 cleanup 函数在它被杀死之前调用 b.py 但我无法让它工作。

我还在 os.kill 函数中尝试了 SIGKILLSIGINT,但都不适合我。

当前输出(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)

为 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