在Python中,你可以使用subprocess
模塊來調用CMD命令
import subprocess
# 要執行的命令,例如:dir
command = "dir"
# 使用subprocess.run()執行命令
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
# 打印執行結果
print("命令輸出:")
print(result.stdout)
print("錯誤輸出:")
print(result.stderr)
print("返回碼:")
print(result.returncode)
在這個例子中,我們使用subprocess.run()
函數執行了一個簡單的dir
命令,該命令用于列出當前目錄下的文件和文件夾。stdout
、stderr
和text
參數分別用于捕獲命令的標準輸出、錯誤輸出和返回結果。shell=True
表示我們在一個shell環境中執行這個命令。
請注意,使用shell=True
可能會導致安全風險,尤其是在處理用戶提供的數據時。在這種情況下,最好使用命令序列(列表形式)而不是命令字符串,并避免使用shell=True
。例如:
command = ["dir"]
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)