我有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/