在python 2.7中,我想執行一個OS命令(例如UNIX中的'ls -l')並將其輸出保存到文件中。我不希望執行結果顯示在文件以外的其他地方。如何執行OS命令並將結果保存到文件中
這可以在不使用os.system的情況下實現嗎?
在python 2.7中,我想執行一個OS命令(例如UNIX中的'ls -l')並將其輸出保存到文件中。我不希望執行結果顯示在文件以外的其他地方。如何執行OS命令並將結果保存到文件中
這可以在不使用os.system的情況下實現嗎?
使用subprocess.check_call
重定向標準輸出到文件對象:
from subprocess import check_call, STDOUT, CalledProcessError
with open("out.txt","w") as f:
try:
check_call(['ls', '-l'], stdout=f, stderr=STDOUT)
except CalledProcessError as e:
print(e.message)
無論你在命令返回非零出口時做什麼除了應該處理tatus。如果你想爲標準輸出文件和其他處理標準錯誤打開兩個文件:
from subprocess import check_call, STDOUT, CalledProcessError, call
with open("stdout.txt","w") as f, open("stderr.txt","w") as f2:
try:
check_call(['ls', '-l'], stdout=f, stderr=f2)
except CalledProcessError as e:
print(e.message)
假設你只是想運行一個命令有它的輸出去到一個文件,你可以使用subprocess
模塊像
subprocess.call("ls -l > /tmp/output", shell=True)
雖然不會重定向stderr
您可以打開一個文件,並把它傳遞給subprocess.call
爲stdout
參數,並運往stdout
必去的文件,而不是輸出。
import subprocess
with open("result.txt", "w") as f:
subprocess.call(["ls", "-l"], stdout=f)
它不會捕捉任何輸出stderr
儘管這必須通過傳遞一個文件subprocess.call
爲stderr
參數被重定向。我不確定您是否可以使用相同的文件。
你是什麼意思「隱藏標準輸出的執行結果」?你只是想讓這些結果進入一個文件,而不是顯示在你的程序中的屏幕/其他地方? –
@eric事實上,我不希望結果顯示在屏幕上或文件以外的其他地方。 – lisa1987
你想重定向標準輸出還是標準輸出和標準錯誤? –