Using "apt-get install xxx" inside Python script

Federico Sciarretta picture Federico Sciarretta · Dec 12, 2011 · Viewed 13.9k times · Source

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.

Answer

Russell Dias picture Russell Dias · Dec 12, 2011

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 :) )