gpt4 book ai didi

python - atexit 处理程序不响应信号

转载 作者:可可西里 更新时间:2023-11-01 09:32:25 25 4
gpt4 key购买 nike

我有两个 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中多放一些sleep,否则子进程在父进程退出之前没有机会清理:

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

关于python - atexit 处理程序不响应信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com