如何在Python中使用子进程重定向输出?
发布于 2021-02-02 23:17:49
我在命令行中执行的操作:
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
关注者
0
被浏览
120
1 个回答
-
更新:不鼓励使用
os.system
,尽管在Python 3中仍然可用。用途
os.system:
os.system(my_cmd)
如果你确实要使用子流程,请使用以下解决方案(大部分内容来自子流程的文档):
p = subprocess.Popen(my_cmd, shell=True) os.waitpid(p.pid, 0)
OTOH,你可以完全避免系统调用:
import shutil with open('myfile', 'w') as outfile: for infile in ('file1', 'file2', 'file3'): shutil.copyfileobj(open(infile), outfile)