1

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • returncode ```Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully.``` – static const Jun 18 '19 at 20:47
  • 1
    This depends on your `/etc/sudoers` file. By default, applications without a TTY aren't allowed to use sudo at all. Maybe use `gksudo`, which is explicitly intended for graphical use, instead? – Charles Duffy Jun 18 '19 at 20:47
  • In order to get subprocess to output to stdout, you have to give it arguments: `subprocess.run([...], stdout=subprocess.PIPE, stderr=subprocess.PIPE)`. [see this answer](https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output) – Green Cloak Guy Jun 18 '19 at 20:48
  • 1
    @GreenCloakGuy, however, sudo prompts for passwords on the TTY, not via stdin/stdout, so I don't see why that would be relevant. – Charles Duffy Jun 18 '19 at 20:48
  • @CharlesDuffy For easier debugging, mostly – Green Cloak Guy Jun 18 '19 at 20:49
  • 1
    gksudo is deprecated since Ubuntu 18.04. The new method is pkexec. Thanks alot @CharlesDuffy for your suggestion. – Ahmed.Elsayed Jun 18 '19 at 21:26

1 Answers1

2

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)