在Python中,你可以使用os
和subprocess
模塊來執行Linux指令
os.system(command)
:執行系統命令,但不返回執行結果。os.popen(command).read()
:執行系統命令并讀取輸出結果。subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
:使用run()
函數執行系統命令,并返回一個CompletedProcess
對象,其中包含命令的輸出和錯誤信息。subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
:使用Popen()
函數執行系統命令,并允許你與命令的輸出和錯誤流進行交互。以下是一些示例:
import os
import subprocess
# 使用os.system執行命令
os.system("ls")
# 使用os.popen執行命令并讀取輸出
output = os.popen("ls").read()
print(output)
# 使用subprocess.run執行命令并獲取輸出
result = subprocess.run("ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(result.stdout)
# 使用subprocess.Popen執行命令并與輸出流交互
process = subprocess.Popen("ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = process.communicate()
if process.returncode != 0:
print(f"Error: {error}")
else:
print(output)
請注意,在使用這些方法時,你需要確保你的Python腳本具有執行系統命令所需的權限。在某些情況下,你可能需要使用sudo
或以其他方式提升權限。