如何在Python中使用子进程重定向输出?

2024-02-05

我在命令行中执行的操作:

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

In 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)

正如其他人指出的那样,使用外部命令如cat为此目的是完全无关的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中使用子进程重定向输出? 的相关文章

随机推荐