首页 > 解决方案 > 子进程终止时如何运行函数?

问题描述

我有 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 位)

标签: pythonsubprocessatexit

解决方案


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

看起来你需要import signal然后做proc.send_signal(signal.CTRL_C_EVENT)而不是proc.terminate()


推荐阅读