在 Python 中使用 Subprocess 重定向输出
要使用 subprocess 将输出重定向到文件,请使用 stdout 参数来指定文件句柄。
import subprocess # Specify the input files and command input_files = ['file1', 'file2', 'file3'] command = ['cat'] + input_files # Create a file handle for the output file with open('myfile', "w") as outfile: # Redirect output to the file handle subprocess.run(command, stdout=outfile)
在 Python 3.5 及更高版本中,这种方法优于使用 subprocess.call 和args 参数使用 shlex.split 从字符串转换而来。这可确保输出正确重定向到文件。
请注意,在这种情况下不需要使用 cat 等外部命令,因为可以直接在 Python 中实现相同的功能。
以上是如何在 Python 中使用子进程将输出重定向到文件?的详细内容。更多信息请关注PHP中文网其他相关文章!