Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
gnome-terminal
#1
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
Reply
#2
sudo needs a password.
Reply
#3
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?
Reply
#4
(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
Reply
#5
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)
« We can solve any problem by introducing an extra level of indirection »
Reply
#6
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  gnome terminal playing with python jmex 12 6,339 Feb-03-2021, 01:38 PM
Last Post: Axel_Erfurt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020