在Python中,os.system()
函數用于執行系統命令
subprocess
模塊:subprocess
模塊提供了更強大和靈活的方式來執行系統命令。你可以使用subprocess.run()
函數來執行命令并捕獲輸出和錯誤。例如:
import subprocess
command = "your_command_here"
process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
if process.returncode != 0:
print(f"Error occurred: {process.stderr}")
else:
print(f"Command output: {process.stdout}")
在這個例子中,your_command_here
是你要執行的命令。stdout
和stderr
參數用于捕獲命令的輸出和錯誤。text=True
表示以文本模式處理輸出,而不是字節模式。shell=True
表示在shell中執行命令。
os.system()
函數返回命令的返回碼。如果返回碼為0,表示命令執行成功;否則,表示命令執行失敗。例如:
import os
command = "your_command_here"
return_code = os.system(command)
if return_code != 0:
print(f"Error occurred with return code {return_code}")
else:
print("Command executed successfully")
在這個例子中,your_command_here
是你要執行的命令。如果return_code
不等于0,表示命令執行失敗。