【发布时间】: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