在Python中,你可以使用subprocess
模塊來執行外部命令
import subprocess
# 執行外部命令,例如ls命令(在Unix/Linux系統中)
command = "ls"
output = subprocess.check_output(command, shell=True, text=True)
print(output)
# 執行外部命令,例如dir命令(在Windows系統中)
command = "dir"
output = subprocess.check_output(command, shell=True, text=True)
print(output)
在這個例子中,我們使用了subprocess.check_output()
函數來執行外部命令。shell=True
表示我們允許在shell環境中執行命令,這在執行包含管道、重定向等特性的命令時非常有用。text=True
表示我們希望以文本形式接收輸出,而不是字節形式。
請注意,使用shell=True
可能會導致安全風險,特別是在處理用戶提供的輸入時。在這種情況下,最好使用命令序列(列表形式)而不是命令字符串,并避免使用shell=True
。例如:
import subprocess
command = ["ls", "-l"] # 使用命令序列而不是命令字符串
output = subprocess.check_output(command, text=True)
print(output)
這樣可以確保你的應用程序更加安全。