在Python中,subprocess.Popen類可以重定向標準錯誤流,通過參數stderr來實現??梢詫tderr參數設置為subprocess.PIPE來捕獲標準錯誤流的輸出,或者將stderr參數設置為一個文件對象來將標準錯誤流的輸出寫入到指定的文件中。下面是一個例子:
import subprocess
# 執行一個命令,并將標準錯誤輸出到標準輸出中
process = subprocess.Popen(["ls", "non_existent_dir"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, _ = process.communicate()
print(output.decode())
# 將標準錯誤輸出到文件中
with open("error.log", "w") as error_file:
process = subprocess.Popen(["ls", "non_existent_dir"], stderr=error_file)
process.wait()