简体   繁体   English

从图形Python程序使用sudo运行命令

[英]Run command with sudo from a graphical Python program

I want to create a graphical python application that can execute some external programs on Linux without showing the terminal. 我想创建一个图形化的python应用程序,该应用程序可以在Linux上执行一些外部程序而无需显示终端。

First, I tried to use subprocess.run() to see if it actually works, but Python 3.7.3 shows no results to the code I wrote. 首先,我尝试使用subprocess.run()来查看它是否真正起作用,但是Python 3.7.3对我编写的代码未显示任何结果。

import subprocess
subprocess.run(['sudo', 'apt', 'update'])

I changed it to see any results: 我更改了它以查看任何结果:

import subprocess
a = subprocess.run(['sudo', 'apt', 'update'])
print(a)

but it shows this result instantly: 但它会立即显示此结果:

CompletedProcess(args=['sudo', 'apt', 'update'], returncode=1)

This script will take at least 5 seconds to be finished, and it requires sudo privileges to be able to run it in the first place, so I don't think that Python shell executed this script. 该脚本至少需要5秒钟才能完成,并且首先需要sudo权限才能运行它,因此我认为Python shell无法执行此脚本。

Using pkexec instead of sudo fixed my issue. 使用pkexec而不是sudo解决了我的问题。 Thanks for everyone tried to help me especially @Charles Duffy. 感谢所有试图帮助我的人,特别是@Charles Duffy。

Now it looks like this: 现在看起来像这样:

import subprocess
result = subprocess.run(['pkexec', 'apt', 'update'], stdout=subprocess.PIPE)
print(result.stdout)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM