如何在 Python 中使用子进程重定向输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4965159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect output with subprocess in Python?
提问by catatemypythoncode
What I do in the command line:
我在命令行中执行的操作:
cat file1 file2 file3 > myfile
What I want to do with python:
我想用python做什么:
import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
采纳答案by Marcelo Cantos
UPDATE: os.system is discouraged, albeit still available in Python 3.
更新:不鼓励使用 os.system,尽管在 Python 3 中仍然可用。
Use os.system:
使用os.system:
os.system(my_cmd)
If you really want to use subprocess, here's the solution (mostly lifted from the documentation for subprocess):
如果您真的想使用子流程,这是解决方案(主要来自子流程的文档):
p = subprocess.Popen(my_cmd, shell=True)
os.waitpid(p.pid, 0)
OTOH, you can avoid system calls entirely:
OTOH,您可以完全避免系统调用:
import shutil
with open('myfile', 'w') as outfile:
for infile in ('file1', 'file2', 'file3'):
shutil.copyfileobj(open(infile), outfile)
回答by SingleNegationElimination
@PoltoS I want to join some files and then process the resulting file. I thought using cat was the easiest alternative. Is there a better/pythonic way to do it?
@PoltoS 我想加入一些文件,然后处理生成的文件。我认为使用 cat 是最简单的选择。有没有更好的/pythonic方法来做到这一点?
Of course:
当然:
with open('myfile', 'w') as outfile:
for infilename in ['file1', 'file2', 'file3']:
with open(infilename) as infile:
outfile.write(infile.read())
回答by Ryan C. Thompson
In Python 3.5+to redirect the output, just pass an open file handle for the stdoutargument to subprocess.run:
在Python 3.5+中重定向输出,只需将参数的打开文件句柄传递stdout给subprocess.run:
# Use a list of args instead of a string
input_files = ['file1', 'file2', 'file3']
my_cmd = ['cat'] + input_files
with open('myfile', "w") as outfile:
subprocess.run(my_cmd, stdout=outfile)
As others have pointed out, the use of an external command like catfor this purpose is completely extraneous.
正如其他人指出的那样,cat为此目的使用外部命令是完全无关紧要的。
回答by DJJ
One interesting case would be to update a file by appending similar file to it. Then one would not have to create a new file in the process. It is particularly useful in the case where a large file need to be appended. Here is one possibility using teminal command line directly from python.
一种有趣的情况是通过向文件附加类似文件来更新文件。这样就不必在此过程中创建新文件了。它在需要附加大文件的情况下特别有用。这是直接从 python 使用终端命令行的一种可能性。
import subprocess32 as sub
with open("A.csv","a") as f:
f.flush()
sub.Popen(["cat","temp.csv"],stdout=f)
回答by wyx
size = 'ffprobe -v error -show_entries format=size -of default=noprint_wrappers=1:nokey=1 dump.mp4 > file'
proc = subprocess.Popen(shlex.split(size), shell=True)
time.sleep(1)
proc.terminate() #proc.kill() modify it by a suggestion
size = ""
with open('file', 'r') as infile:
for line in infile.readlines():
size += line.strip()
print(size)
os.remove('file')
When you use subprocess, the process must be killed.This is an example.If you don't kill the process , filewill be empty and you can read nothing.It can run on Windows.I can`t make sure that it can run on Unix.
当你使用子进程时,进程必须被杀死。这是一个例子。如果你不杀死进程,文件将是空的,你什么也读不到。它可以在Windows上运行。我不能确保它可以在 Unix 上运行。

