溫馨提示×

python外部命令如何使用管道符

小樊
133
2024-12-12 02:29:40
欄目: 編程語言

在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變量中。最后,我們打印出每個命令的輸出以及組合命令的輸出。

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