在Python中,你可以使用subprocess
模塊來執行外部命令并使用管道符
import subprocess
# 執行外部命令并捕獲輸出
command1 = "echo 'Hello, World!'"
command2 = "grep 'World'"
# 使用subprocess.run()執行外部命令
result1 = subprocess.run(command1, stdout=subprocess.PIPE, text=True, shell=True)
result2 = subprocess.run(command2, stdout=subprocess.PIPE, text=True, shell=True)
# 獲取命令輸出
output1 = result1.stdout.strip()
output2 = result2.stdout.strip()
print("Output of command1:", output1)
print("Output of command2:", output2)
# 使用管道符將兩個命令的輸出連接起來
combined_output = subprocess.run(f"{command1} | {command2}", stdout=subprocess.PIPE, text=True, shell=True)
# 獲取組合命令的輸出
combined_output_str = combined_output.stdout.strip()
print("Combined output:", combined_output_str)
在這個示例中,我們首先執行了兩個外部命令:echo 'Hello, World!'
和 grep 'World'
。然后,我們使用管道符將這兩個命令的輸出連接起來,并將結果存儲在combined_output
變量中。最后,我們打印出每個命令的輸出以及組合命令的輸出。