我正在尝试生成一个在主进程关闭后仍应运行的子进程。这部分工作正常,但如果我将此进程的输出重定向到文件,我无法再次启动该脚本,因为该进程仍会阻止日志文件。
这个简短的例子演示了这个问题:在这种情况下,第二个进程是“notepad”,由“other.cmd”启动。主进程/脚本是“test_it.py”,由“start_it.cmd”启动。
start_it.cmd
@python test_it.py > test.log
test_IT.朋友
import subprocess
from subprocess import DEVNULL, STDOUT
subprocess.Popen(["other.cmd"], stdin=DEVNULL, stdout=DEVNULL, stderr=STDOUT)
other.cmd
start notepad
当start_it.cmd
第二次执行时,它将失败并显示此错误消息“进程无法访问该文件,因为它正被另一个进程使用”。
如何启动子进程以使其不阻止日志文件?
使用管道的解决方案。 multiplexer.py
with open('log.txt', 'a') as outputFile:
while True:
data = sys.stdin.read(1024)
if None == data:
break
outputFile.write(data)
start_it.cmd
@python test_it.py | python multiplexer.py
其他一切都保持不变。
我找到了一个接近我原定的解决方案:
subprocess.Popen("explorer other.cmd", shell=True)
通过让资源管理器启动.cmd文件,可以成功地将调用的.cmd从原始进程中分离出来。因此不会保持日志文件打开。