So I'm trying to execute a simple command here it does run but I come up with errors
os.system("gnome-terminal -e 'sudo apt update'")
# Option “-e” is deprecated and might be removed in a later version of gnome-terminal.
# Use “-- ” to terminate the options and put the command line to execute after it.
If I do anything it says the program just doesn't work nothing happens I removed the E and it won't function I replaced the E with the two dashes and is still one function
any help here would be appreciated
This worked for me:
import os
os.system("gnome-terminal -e 'sudo apt update'")
os.system("gnome-terminal -e 'sudo apt upgrade'")
But I could not link the 2 commands with &&
Why would you do that from Python?
(May-10-2024, 05:42 PM)Axel_Erfurt Wrote: [ -> ]sudo needs a password.
yes I know that when the terminal opens up I get the error message
when I enter my password it does just fine
I don't understand why am getting the error codes
You could perhaps invoke the sudo command without using the gnome terminal. I found in my notes an old technique to invoke sudo from Python (the code could be modernized)
import getpass
import subprocess as sp
COMMAND = ['ls'] # replace this with ['apt', 'update']
mypass = getpass.getpass('This needs administrator privileges: ')
proc = sp.Popen(['sudo', '-kS'] + COMMAND, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, encoding='utf8')
proc.stdin.write(mypass + '\n')
o, e = proc.communicate()
if proc.returncode:
print('command failed')
else:
print('success')
print(o)
print(e)
Should not use
os.system
anymore,
subprocess has replaced it in a safer and better way a long time ago.
Here are two way both tested and ok for me.
import subprocess
command = subprocess.run(['gnome-terminal', '--', 'bash', '-c', 'sudo apt-get install --only-upgrade ack; sleep 20'], encoding='utf-8', capture_output=True)
print(command.stdout)
Not using gnome-terminal and do it directly with subprocess.
Here use
-S
to get password via
stdin
.
# sudo1.py
import subprocess
password = 'xxxxxx'
command = subprocess.run(['sudo', '-S', 'apt-get', 'install', '--only-upgrade', 'ack'], input=password, text=True, capture_output=True)
print(command.stdout)
Output:
tom@tom:~/Documents/py_files$ python sudo1.py
Reading package lists...
Building dependency tree...
Reading state information...
ack is already the newest version (2.22-1).
0 upgraded, 0 newly installed, 0 to remove and 809 not upgraded