pythonlinuxoperating-systemsudogksudo

python script to check and install packages


I am trying to write a python script to check and install packages in linux. I have two questions:

First, I tried to write the below code to check the packages, but non is working. What I am missing is how can I convert printing into terminal to a variable that i can detect. Please find the code.

Trial #1

import apt
import os

x = os.system('apt-cache policy python3.6-dev')
if x>0:
    print('installed')
else:
    print('not installed')

Trial #2

import os 

os.system('dpkg-query -l | grep python3.6-dev | wc -l')
x = os.system('echo $?')
if x>0:
    print('installed')
else:
    print('not installed')

Second, I am tried to write a python script to install. But, for linux we always use sudo. I wrote this code in the past which uses gksudo. It was working but now it's not working because they removed gksudu. How can I modify this code and what else can i use instead of gksudo

File #1 (call RAM.py file)

import os
os.system('gksudo python RAM.py')

File #2 (RAM file)

import os

# install
os.system('sudo apt-get install python3.6-dev')

Solution

  • First of all, I would recommend you to use subprocess module instead of os. In order to execute a shell command and capture the return code, stdout and stderr, you can try:

    from subprocess import run, PIPE
    res = run('apt-cache policy python3.6-dev', shell=True, stdout=PIPE, stderr=PIPE, check=True)
    print(res.returncode, res.stdout, res.stderr)
    

    where check(optional) is to raise exception if the execution failed (returncode>0).

    In order to run a command with sudo, I would suggest the following:

    password = "my_password"
    base_command = "ls -l" # replace it with your command
    command_with_sudo = f"echo {password} | sudo -S {base_command}"
    res = run(command_with_sudo, shell=True, check=True, stdout=PIPE, stderr=PIPE)
    

    Note that it's very insecure to store your password as a plain text in your code so try to avoid it (you can provide it as an argument to your script/ store it in your environment/ encrypt it somehow - just don't leave it as is in your code)