溫馨提示×

python外部命令如何執行

小樊
104
2024-12-12 03:16:44
欄目: 編程語言

在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)

這樣可以確保你的應用程序更加安全。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女