简体   繁体   中英

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.

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.

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.

Using pkexec instead of sudo fixed my issue. Thanks for everyone tried to help me especially @Charles Duffy.

Now it looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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