在Python中,執行外部命令時,有時需要提升權限
subprocess.run()
函數:import subprocess
# 使用sudo運行外部命令
command = "sudo your_command"
result = subprocess.run(command, shell=True, check=True, text=True)
print(result.stdout)
os.system()
函數:import os
# 使用sudo運行外部命令
command = "sudo your_command"
os.system(command)
subprocess.Popen()
函數:import subprocess
# 使用sudo運行外部命令
command = "sudo your_command"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()
if process.returncode != 0:
print(f"Error occurred: {stderr}")
else:
print(stdout)
請注意,在使用這些方法時,您需要確保Python腳本具有足夠的權限來執行sudo
命令。通常,這意味著您需要在運行此腳本的計算機上使用sudo
運行它。例如,如果您在Linux或macOS上運行此腳本,可以在終端中使用以下命令:
sudo python your_script.py
在Windows上,您可以使用管理員權限運行命令提示符或PowerShell,然后運行Python腳本:
python your_script.py
或者
python your_script.py