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?
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?
You can use the subprocess module to execute the command:
import subprocess
package_name = "<package_name>"
subprocess.run(["sudo", "apt", "install", "-y", package_name], check=True)
Please be very careful to never hardcode your root password into a script. If you want to run this code without password prompt, configure your sudoers accordingly. Just be careful not to create a security nightmare.
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.
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.