首頁 > 後端開發 > Python教學 > 如何在 Python 中使用子程序將輸出重新導向到檔案?

如何在 Python 中使用子程序將輸出重新導向到檔案?

Susan Sarandon
發布: 2024-11-15 20:30:03
原創
929 人瀏覽過

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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板