如何在Python中使用subprocess重定向输出?
我在命令行中做的事情:
cat file1 file2 file3 > myfile
我想用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
6 个回答
6
@PoltoS 我想把一些文件合并在一起,然后处理合并后的文件。我觉得用cat命令是最简单的选择。有没有更好或者更符合Python风格的方法呢?
当然可以:
with open('myfile', 'w') as outfile:
for infilename in ['file1', 'file2', 'file3']:
with open(infilename) as infile:
outfile.write(infile.read())
374
在Python 3.5+中,如果你想改变输出的去向,只需要把一个打开的文件句柄传给subprocess.run
里的stdout
参数就可以了:
# 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)
正如其他人所提到的,使用像cat
这样的外部命令来实现这个目的其实是多余的。
17
更新:虽然在Python 3中仍然可以使用,但不推荐使用 os.system
。
使用 os.system
:
os.system(my_cmd)
如果你真的想用 subprocess,这里有个解决方案(大部分内容来自于 subprocess 的文档):
p = subprocess.Popen(my_cmd, shell=True)
os.waitpid(p.pid, 0)
另一方面,你可以完全避免使用系统调用:
import shutil
with open('myfile', 'w') as outfile:
for infile in ('file1', 'file2', 'file3'):
shutil.copyfileobj(open(infile), outfile)