在Python中,你可以使用subprocess
模塊來執行外部命令并使用管道連接多個命令
import subprocess
# 第一個命令:將輸入的文本轉換為大寫
uppercase_command = "echo 'hello world' | tr '[:lower:]' '[:upper:]'"
# 第二個命令:輸出結果
print_command = "cat -"
# 使用subprocess.run()執行外部命令
result = subprocess.run(uppercase_command, stdout=subprocess.PIPE, text=True)
# 將第一個命令的輸出作為第二個命令的輸入
result = subprocess.run(print_command, stdin=result.stdout, stdout=subprocess.PIPE, text=True)
# 打印最終結果
print(result.stdout)
在這個示例中,我們首先使用echo
命令輸出文本"hello world",然后使用tr
命令將其轉換為大寫。接下來,我們將第一個命令的輸出作為第二個命令(cat -
)的輸入,最后使用print
命令輸出結果。
注意,我們使用了subprocess.PIPE
來捕獲命令的輸出,并將其傳遞給下一個命令。我們還使用了text=True
參數來確保輸出以文本形式(而不是字節形式)處理。