启动不阻止父重定向到的文件的子进程

问题描述 投票:0回答:2

我正在尝试生成一个在主进程关闭后仍应运行的子进程。这部分工作正常,但如果我将此进程的输出重定向到文件,我无法再次启动该脚本,因为该进程仍会阻止日志文件。

这个简短的例子演示了这个问题:在这种情况下,第二个进程是“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第二次执行时,它将失败并显示此错误消息“进程无法访问该文件,因为它正被另一个进程使用”。

如何启动子进程以使其不阻止日志文件?

python windows cmd python-3.4
2个回答
1
投票

使用管道的解决方案。 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

其他一切都保持不变。


0
投票

我找到了一个接近我原定的解决方案:

subprocess.Popen("explorer other.cmd", shell=True)

通过让资源管理器启动.cmd文件,可以成功地将调用的.cmd从原始进程中分离出来。因此不会保持日志文件打开。

© www.soinside.com 2019 - 2024. All rights reserved.