首页 >后端开发 >Python教程 >如何在 Python 中使用子进程将输出重定向到文件?

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

Susan Sarandon
Susan Sarandon原创
2024-11-15 20:30:03920浏览

How to Redirect Output to a File Using Subprocess in Python?

在 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn