python - 子进程终止时如何运行函数?
问题描述
我有 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
到进程,terminate()
这与调用TerminateProcess
WinAPI 方法的方法不同。
看起来你需要import signal
然后做proc.send_signal(signal.CTRL_C_EVENT)
而不是proc.terminate()
推荐阅读
- rpc - 什么取代了 pmap_set 命令?
- c# - 使用 htmlagilitypack 选择特定的 td
- laravel - Laravel 错误:调用字符串上的成员函数 format()
- elasticsearch - 判断elasticsearch恢复失败
- ms-access - MS Access 组合框显示选项卡
- html - SVG 光标有不需要的灰色边缘
- android - 将 ImageButton 放在两个视图组之间
- amazon-web-services - 权限有助于设置用户对 S3 的访问权限
- javascript - IIFE:如果我返回警报而不将其包装在函数中,为什么我的代码会忽略 addEventListener?
- keras - 使用 Keras 添加和访问辅助 tf.Dataset 属性