cyberangles blog

How to Install Packages with apt-get in Python Scripts: Using the apt Library and Hiding Subprocess Output

Automating system setup and configuration is a common task in DevOps, system administration, and software deployment. Often, this involves installing packages via apt-get (the package manager for Debian-based systems like Ubuntu). While you could manually run sudo apt-get install <package>, integrating this into Python scripts streamlines workflows, reduces human error, and enables end-to-end automation.

In this guide, we’ll explore two methods to install packages via Python:

  1. Using the subprocess module to call apt-get directly (traditional but limited).
  2. Using the python-apt library (a more robust, programmatic approach).

We’ll also cover how to hide verbose apt-get output to keep scripts clean, and share best practices for error handling and security.

2026-01

Table of Contents#

  1. Prerequisites
  2. Traditional Approach: Using subprocess to Call apt-get
  3. Drawbacks of the subprocess Approach
  4. Using the python-apt Library
  5. Hiding Output When Using subprocess
  6. Advanced: Combining python-apt with subprocess
  7. Best Practices
  8. Troubleshooting Common Issues
  9. Conclusion
  10. References

Prerequisites#

Before starting, ensure you have:

  • A Debian/Ubuntu-based system (e.g., Ubuntu 20.04+, Debian 10+).
  • Python 3 installed (preinstalled on most Linux systems; verify with python3 --version).
  • Root privileges (most apt operations require sudo).
  • Basic familiarity with Python and the command line.

Traditional Approach: Using subprocess to Call apt-get#

The simplest way to run apt-get in Python is to use the built-in subprocess module, which lets you spawn new processes and interact with their outputs.

Example: Installing a Package with subprocess#

Here’s a basic script to install the curl package using subprocess.run():

import subprocess
 
def install_package(package_name):
    try:
        # Run 'sudo apt-get install -y <package>'
        subprocess.run(
            ["sudo", "apt-get", "install", "-y", package_name],
            check=True  # Raise an error if the command fails
        )
        print(f"Successfully installed {package_name}!")
    except subprocess.CalledProcessError as e:
        print(f"Failed to install {package_name}. Error: {e}")
 
# Usage
install_package("curl")

Explanation:#

  • subprocess.run() executes the command sudo apt-get install -y curl.
  • The -y flag auto-approves prompts (critical for non-interactive scripts).
  • check=True ensures the script raises an error if apt-get fails (e.g., package not found).

Drawbacks of the subprocess Approach#

While subprocess works for simple cases, it has significant limitations:

  1. Unstructured Output: apt-get produces verbose text output, cluttering logs.
  2. Error Handling: Parsing errors from raw output is error-prone (e.g., distinguishing "package not found" from "permission denied").
  3. Lack of Control: No programmatic way to check if a package is already installed, update the package cache, or resolve dependencies.
  4. Security Risks: If package_name is user-provided, unsanitized inputs could lead to command injection attacks (e.g., package_name="curl; rm -rf /").

Using the python-apt Library#

For more control, use python-apt (officially python3-apt), a Python binding for APT (Advanced Package Tool). It lets you interact with the APT cache, check package statuses, and install/remove packages programmatically.

Step 1: Install python-apt#

First, install the library itself (requires sudo):

sudo apt install python3-apt

Step 2: Key Concepts in python-apt#

  • APT Cache: A local database of available packages and their versions.
  • Package Object: Represents a single package (e.g., curl), with attributes like is_installed (boolean) and methods like mark_install().

Step 3: Basic Usage Examples#

Example 1: Check if a Package Is Installed#

Before installing, verify if the package is already present to avoid redundant work:

import apt
 
def is_package_installed(package_name):
    cache = apt.Cache()  # Initialize the APT cache
    cache.open()         # Load package data from the cache
    try:
        package = cache[package_name]
        return package.is_installed
    except KeyError:
        # Package not found in repositories
        return False
 
# Usage
print(is_package_installed("curl"))  # Output: True (if installed) or False

Example 2: Install a Package with python-apt#

To install a package, you’ll need to:

  1. Update the APT cache (to fetch the latest package lists).
  2. Mark the package for installation.
  3. Commit the changes (apply the installation).

Note: APT operations require root privileges. Run the script with sudo.

import apt
import sys
 
def install_package(package_name):
    # Initialize the APT cache
    cache = apt.Cache()
 
    try:
        # Update the cache (equivalent to 'sudo apt update')
        print("Updating package list...")
        cache.update()
        cache.open()  # Reload the cache after updating
 
        # Check if the package exists
        if package_name not in cache:
            print(f"Error: Package '{package_name}' not found.")
            return False
 
        package = cache[package_name]
 
        # Check if already installed
        if package.is_installed:
            print(f"Package '{package_name}' is already installed.")
            return True
 
        # Mark the package for installation
        print(f"Marking '{package_name}' for installation...")
        package.mark_install()  # Auto-resolves dependencies by default
 
        # Commit changes (equivalent to 'sudo apt-get install -y')
        print(f"Installing '{package_name}'...")
        cache.commit()  # Applies the installation
        print(f"Successfully installed '{package_name}'!")
        return True
 
    except apt.cache.LockFailedException:
        print("Error: Could not lock the APT cache. Another APT process is running.")
        return False
    except Exception as e:
        print(f"Installation failed: {str(e)}")
        return False
 
# Usage: Run with sudo (e.g., 'sudo python3 install_script.py')
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: sudo python3 install_script.py <package_name>")
        sys.exit(1)
    install_package(sys.argv[1])

How It Works:#

  • cache.update(): Updates the package list (like sudo apt update).
  • cache.open(): Reloads the cache to reflect updates.
  • package.mark_install(): Flags the package for installation (and resolves dependencies).
  • cache.commit(): Executes the installation (requires root).

Hiding Output When Using subprocess#

Even with python-apt, you may occasionally need subprocess (e.g., adding PPAs or running apt-get with custom flags). To keep scripts clean, hide apt-get’s verbose output.

Method 1: Suppress Output Entirely#

Redirect stdout (standard output) and stderr (error output) to subprocess.DEVNULL:

import subprocess
 
def install_with_hidden_output(package_name):
    try:
        subprocess.run(
            ["sudo", "apt-get", "install", "-y", package_name],
            check=True,
            stdout=subprocess.DEVNULL,  # Hide standard output
            stderr=subprocess.DEVNULL   # Hide error output
        )
        print(f"Installed {package_name} (output hidden).")
    except subprocess.CalledProcessError:
        print(f"Failed to install {package_name}.")
 
install_with_hidden_output("curl")

Method 2: Log Output to a File#

For debugging, redirect output to a log file instead of hiding it:

import subprocess
 
def install_with_log(package_name, log_file="apt_install.log"):
    with open(log_file, "w") as f:
        try:
            subprocess.run(
                ["sudo", "apt-get", "install", "-y", package_name],
                check=True,
                stdout=f,  # Write stdout to log file
                stderr=f   # Write stderr to log file
            )
            print(f"Installed {package_name}. Logs saved to {log_file}.")
        except subprocess.CalledProcessError:
            print(f"Failed to install {package_name}. Check {log_file} for details.")
 
install_with_log("curl")

Advanced: Combining python-apt with subprocess#

Some tasks (e.g., adding PPAs) aren’t supported by python-apt and require subprocess. Combine both tools for full flexibility.

Example: Add a PPA and Install a Package#

Suppose you want to install docker-ce from Docker’s official PPA:

import apt
import subprocess
 
def add_ppa_and_install(ppa, package_name):
    # Step 1: Add the PPA using subprocess
    try:
        print(f"Adding PPA: {ppa}...")
        subprocess.run(
            ["sudo", "add-apt-repository", "-y", ppa],
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )
    except subprocess.CalledProcessError:
        print(f"Failed to add PPA: {ppa}")
        return False
 
    # Step 2: Install the package using python-apt
    cache = apt.Cache()
    cache.update()  # Update cache to include the new PPA
    cache.open()
    if package_name in cache:
        package = cache[package_name]
        if not package.is_installed:
            package.mark_install()
            cache.commit()
            print(f"Installed {package_name} from PPA.")
            return True
        else:
            print(f"{package_name} is already installed.")
            return True
    else:
        print(f"{package_name} not found in repositories.")
        return False
 
# Usage: Add Docker PPA and install docker-ce
add_ppa_and_install(
    ppa="deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable",
    package_name="docker-ce"
)

Best Practices#

  1. Run with sudo: APT operations (install, update) require root privileges.
  2. Check Installation Status First: Avoid redundant installs with is_installed.
  3. Update the Cache: Always run cache.update() before installing to fetch the latest package versions.
  4. Sanitize Inputs: If using subprocess with user-provided package names, validate inputs to prevent command injection.
  5. Handle Exceptions: Catch errors like LockFailedException (APT cache locked) or KeyError (package not found).

Troubleshooting Common Issues#

ErrorCauseFix
Permission deniedScript not run with sudo.Run with sudo python3 script.py.
Package not foundPackage name is incorrect or not in repositories.Verify the package name or add the required PPA.
Could not lock the cacheAnother APT process (e.g., apt-get, software-updater) is running.Wait for the process to finish or kill it with sudo killall apt apt-get.
Broken dependenciesConflicting packages or corrupted cache.Run sudo apt --fix-broken install or use cache.commit(auto_fix=True) in python-apt.

Conclusion#

For most use cases, python-apt is superior to subprocess for installing packages in Python scripts. It offers granular control, cleaner error handling, and avoids messy output. When subprocess is necessary (e.g., adding PPAs), suppress output with subprocess.DEVNULL or log to a file.

By following the best practices outlined here, you can build robust, automated system setup scripts with confidence.

References#