Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "apt-get install xxx" inside Python script

currently I need to install some package using apt or rpm, according the OS. I saw the lib "apt" to update or upgrade the system, but it is possible use it to install a single package?

I was trying to use too "subprocess":

subprocess.Popen('apt-get install -y filetoinstall', shell=True, stdin=None, stdout=None, stderr=None, executable="/bin/bash")

But this command shows all process in the shell, I cannot hide it.

Thank you for your help.

like image 554
Federico Sciarretta Avatar asked Dec 12 '11 22:12

Federico Sciarretta


People also ask

What is sudo apt-get install?

apt-get is a command-line tool which helps in handling packages in Linux. Its main task is to retrieve the information and packages from the authenticated sources for installation, upgrade and removal of packages along with their dependencies. Here APT stands for the Advanced Packaging Tool.

How do I fix the apt-get command not found?

After installing the APT package, check the /usr/bin/ directory to ensure if it had properly installed. If the file is empty, then run the locate apt-get command again. If no result is shown, there is no alternative but to reinstall the operating system. This might fix the problem.

What is Python apt package?

Python APT's library provides access to almost every functionality supported by the underlying apt-pkg and apt-inst libraries. This means that it is possible to rewrite frontend programs like apt-cdrom in Python, and this is relatively easy, as can be seen in e.g. Writing your own apt-cdrom.


2 Answers

You can use check_call from the subprocess library.

from subprocess import STDOUT, check_call
import os
check_call(['apt-get', 'install', '-y', 'filetoinstall'],
     stdout=open(os.devnull,'wb'), stderr=STDOUT) 

Dump the stdout to /dev/null, or os.devnull in this case.

os.devnull is platform independent, and will return /dev/null on POSIX and nul on Windows (which is not relevant since you're using apt-get but, still good to know :) )

like image 77
Russell Dias Avatar answered Oct 14 '22 02:10

Russell Dias


This is meant as an addition to Russell Dias's accepted answer. This adds a try and except block to output actionable error information rather than just stating there was an error.

from subprocess import check_call, CalledProcessError
import os
try:
    check_call(['apt-get', 'install', '-y', 'filetoinstall'], stdout=open(os.devnull,'wb'))
except CalledProcessError as e:
    print(e.output)
like image 22
saltchicken Avatar answered Oct 14 '22 01:10

saltchicken