Python 如何使用子进程启动命令,并在某个文件中取消阻止输出?

Python 如何使用子进程启动命令,并在某个文件中取消阻止输出?,python,Python,我正在尝试使用子流程在命令行上启动一个命令,我希望将其输出写入某个文件。因此,换句话说,我希望在python中执行以下命令: python my_code.py --arg1 > output.txt 我尝试了以下方法: import subprocess cwd = "/home/path/to/the/executable" cmd = "python my_code.py --arg1" with open('output.txt', "w") as outfile: su

我正在尝试使用
子流程
在命令行上启动一个命令,我希望将其输出写入某个文件。因此,换句话说,我希望在python中执行以下命令:

python my_code.py --arg1 > output.txt
我尝试了以下方法:

import subprocess
cwd = "/home/path/to/the/executable"
cmd = "python my_code.py --arg1"
with open('output.txt', "w") as outfile:
    subprocess.Popen(cmd.split(), stdout=outfile, cwd = cwd)
但是输出文件仍然是空的。否则怎么做(不阻塞!)

补充:


我的猜测是,输出文件已经创建,但在上述代码完成后将立即关闭。因此,没有输出到该文件…

sys.stdout
在默认情况下是缓冲的。您可以通过将
-u
传递到
python
来禁用它

import subprocess
cwd = "/home/path/to/the/executable"
cmd = "python -u my_code.py --arg1"
with open('output.txt', "w") as outfile:
    subprocess.Popen(cmd.split(), stdout=outfile, cwd = cwd)

默认情况下,
sys.stdout
是缓冲的。您可以通过将
-u
传递到
python
来禁用它

import subprocess
cwd = "/home/path/to/the/executable"
cmd = "python -u my_code.py --arg1"
with open('output.txt', "w") as outfile:
    subprocess.Popen(cmd.split(), stdout=outfile, cwd = cwd)

什么是
my_code.py
?这是一个python脚本(服务),我想从另一段代码开始。这只是一些代码,没关系…
subprocess.Popen(cmd.split(),stdout=outfile,cwd=cwd)。wait()
我正在寻找一种非阻塞的方法来实现这一点。我不想等到调用
my_code.py
完成。我希望上面的代码片段在完成后尽快结束……我在搜索时发现了一些有趣的东西。什么是
my_code.py
?这是一个python脚本(服务),我想从另一段代码开始。这只是一些代码,没关系…
subprocess.Popen(cmd.split(),stdout=outfile,cwd=cwd)。wait()
我正在寻找一种非阻塞的方法来实现这一点。我不想等到调用
my_code.py
完成。我希望上面的代码片段在完成后尽快结束……我在搜索时发现了一些有趣的东西。这是一个很好的答案,但仅当您想要“实时”更新文件时才需要。系统故意延迟文件写入,因为这样效率更高。这是一个很好的答案,但仅当您希望“实时”更新文件时才需要。系统故意延迟文件写入,因为这样效率更高。