【问题标题】:How to run a function when a subprocess is terminated?子进程终止时如何运行函数?
【发布时间】:2018-05-15 02:10:13
【问题描述】:

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

【问题讨论】:

    标签: python subprocess atexit


    【解决方案1】:

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

    看来您需要先import signal,然后再使用proc.send_signal(signal.CTRL_C_EVENT) 而不是proc.terminate()

    【讨论】:

    • 是的,我按下了Ctrl+C。非常感谢您的回答!现在可以使用了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2017-08-14
    • 2015-06-27
    • 2021-12-05
    相关资源
    最近更新 更多