在不使用sudo运行execute_command的情况下,可以使用以下方法解决:
import subprocess
command = 'your_command'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if process.returncode == 0:
print(output.decode('utf-8'))
else:
print(error.decode('utf-8'))
这将执行你的命令并获取输出。请注意,这种方法可能需要用户手动处理权限问题。
在一个独立的脚本中,命名为"sudo_script.py":
import subprocess
command = 'your_command'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if process.returncode == 0:
print(output.decode('utf-8'))
else:
print(error.decode('utf-8'))
在主程序中调用该脚本:
import subprocess
command = ['sudo', 'python', 'sudo_script.py']
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if process.returncode == 0:
print(output.decode('utf-8'))
else:
print(error.decode('utf-8'))
这将在需要sudo权限的部分使用sudo运行脚本,并获取输出。请确保在运行主程序时已经输入了sudo密码。