python - 当子进程终止时如何运行函数?

标签 python subprocess atexit

我有2个python代码,其中一个是mar.py,另一个是sub.py

## mar.py
import os
import subprocess
import time

print('MASTER PID: ', os.getpid())

proc = subprocess.Popen(["D:\Miniconda3\python.exe", r"C:\Users\J\Desktop\test\sub.py"], shell=False)

def terminator():
    proc.terminate()

time.sleep(5)
terminator()

mar.py 只需使用 sub.py 创建一个子进程并在 5 秒内终止它。

## sub.py
import atexit
import time
import os

print('SUB PID: ', os.getpid())

os.chdir("C:\\Users\\J\\Desktop\\test")

def handle_exit():
    with open("foo.txt", "w") as f:
        f.write("Life is too short, you need python")

atexit.register(handle_exit)

while True:
    print('alive')
    time.sleep(1)

我以为 foo.txt 会在 sub.py 的子进程终止之前创建,但什么也没发生。如果我单独运行 sub.py 并终止它,它会按照我的计划创建 foo.txt。是什么造成了这种差异?即使它作为子进程运行,我怎样才能让它创建 foo.txt

我使用的是 Windows 10(64 位)和 Python 3.6.5(32 位)

最佳答案

当你说你“终止”sub.py时,这是否意味着你按了Ctrl+C?在 Windows 上,这实际上将 CTRL_C_EVENT 发送到进程,与调用 TerminateProcess WinAPI 方法的 terminate() 方法不同。

看起来您需要导入信号,然后执行proc.send_signal(signal.CTRL_C_EVENT)而不是proc.terminate()

关于python - 当子进程终止时如何运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341353/

相关文章:

python - 在 Kivy 中创建一条动态绘制的线

python-3.x - 往返 2 个 Python 子进程的循环管道

python - 如何在 Python 中使用子进程重定向输出?

python - 检测子进程何时等待输入

python - 如何注册一个仅在我的 Python 程序*成功*退出时调用的函数?

.NET 代码在正常进程退出时执行?

c++ - 从全局对象的构造函数调用时的 std::atexit 排序

Python Gtk3 控制按钮大小

python - 用系列更新数据框

python - hombrew 升级后 pip3 消失了