在Python中,你可以使用subprocess
模塊來調用命令行
import subprocess
# 要執行的命令行命令,例如:dir(Windows)或ls(Linux/macOS)
command = "dir" # 或者 "ls" 如果你在Linux/macOS上運行此代碼
# 使用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)
注意:在使用shell=True
時,請確保你信任要執行的命令,因為它可能會導致安全漏洞。避免在不受信任的輸入上使用shell=True
。