'Installing Linux packages via Python?

I can install packages with Bash like this:

    sudo apt install -y <package_name>

How can I do this with Python? Should I execute Bash script from Python or is there a native way to do this?



Solution 1:[1]

Python has an inbuilt module named os which has a function called system(). Using the system function we can install linux packages.
The Following code is tested on a ubuntu system

import os
try:
    os.system('sudo apt install -y <package_name>')
except:
    exit("Failed to install the <package_name>")

For a sudo user the terminal will ask for the root password. If the process of installation somehow gets failed in the middle of the installation then the code will exit with the error message in the except region.
Note-: Don't save your root password in the script, it may cause security and privacy issues.

Solution 2:[2]

bashCommand = "apt-get install -y <program>"
import subprocess
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()enter code here

You can execute it from python, but you have to run the python script with sudo. There might be a library to do this natively, but I don't know how it would be able to install software without either: requiring you to give the password for sudo when installing, or when the python script is started. Otherwise anyone could install software with a Python script!

Be very cautious about where you put this kind of code. For a personal script, or some kind of installation script for the rest of your python code, it's fine. I would not put this in some server back-end code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 arowell