2

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?

2
  • "How can I do this with Python?" -- Just because you can, doesn't mean you should. Commented Aug 20, 2019 at 16:10
  • Are you saying this for security or for performance reasons? Commented Aug 23, 2019 at 17:43

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Huh, you can actually use sudo in a subprocess. I tested it because I did not think it would work. An alternative to storing passwords is using suid.
Done it many times in the past, works great for self unpacking/installing scripts on Raspberry Pis.
0

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.

Comments

-1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.