溫馨提示×

python外部命令如何處理輸出結果

小樊
97
2024-12-12 02:53:39
欄目: 編程語言

在Python中,你可以使用subprocess模塊來執行外部命令并處理其輸出結果

import subprocess

# 執行外部命令
command = "echo 'Hello, World!'"
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

# 獲取命令的輸出結果
stdout, stderr = process.communicate()

# 將輸出結果從字節轉換為字符串
stdout_str = stdout.decode('utf-8')
stderr_str = stderr.decode('utf-8')

print("Output:", stdout_str)
print("Error:", stderr_str)

# 等待命令執行完成
return_code = process.wait()
print("Return code:", return_code)

在這個示例中,我們使用subprocess.Popen執行了一個簡單的echo命令。stdoutstderr參數分別用于捕獲命令的標準輸出和標準錯誤輸出。shell=True表示我們在一個shell環境中執行這個命令。

process.communicate()方法用于等待命令執行完成并獲取輸出結果。這個方法返回一個包含標準輸出和標準錯誤輸出的元組。我們可以使用decode()方法將輸出結果從字節轉換為字符串。

最后,我們使用process.wait()方法等待命令執行完成并獲取返回代碼。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女