简体   繁体   English

在 Windows 上使用 python 启动分离的无限进程并将输出通过管道传输到文件中

[英]start detached infinite process with python on windows and pipe the output into a file

I am trying to start a process with python that runs infinitely and pipe it's output into a file.我正在尝试使用无限运行的 python 启动一个进程,并将它的输出通过管道传输到一个文件中。 The new created process should keep running after the python executable exits.在 python 可执行文件退出后,新创建的进程应该继续运行。 I am able to start a process and keep it running when python exits with this code:当 python 使用以下代码退出时,我能够启动一个进程并保持它运行:

subprocess.Popen(command_list, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_BREAKAWAY_FROM_JOB)

Now I am trying to pipe the output of the started process into a file, but i can't get it working together with detaching the process.现在我正在尝试将已启动进程的输出通过管道传输到一个文件中,但是我无法通过分离进程来让它一起工作。

Any suggestions on how to achieve this ?关于如何实现这一目标的任何建议?

please note that i am trying to achieve this on Windows.请注意,我正在尝试在 Windows 上实现这一目标。

Have you tried just redirecting stderr and stdout to two files:您是否尝试过将stderrstdout重定向到两个文件:

from subprocess import Popen

from subprocess import DEVNULL
from subprocess import DETACHED_PROCESS
from subprocess import CREATE_NEW_PROCESS_GROUP
from subprocess import CREATE_BREAKAWAY_FROM_JOB

command_list = ...

creationflags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB

with open("stderr.txt", mode="wb") as out, open("stdout.txt", mode="wb") as err:
    Popen(command_list, creationflags=creationflags, stdin=DEVNULL, stdout=out, stderr=err)

Make sure to check stderr.txt and stdout.txt , since the output from your process could be redirected to either.确保检查stderr.txtstdout.txt ,因为您的进程的输出可以重定向到任一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM