Execute unrar in Python Using subprocess

Extracting RAR archives directly within Python is commonly accomplished by invoking the system's unrar command-line utility via the built-in subprocess module. This approach avoids heavy third-party dependencies while leveraging the full speed and features of the official extraction binary. This guide explains how to call unrar securely, pass extraction flags, capture execution output, and handle errors using subprocess.run.

Prerequisites

The unrar command-line utility must be installed and available in your system's PATH. You can verify this by running unrar in your terminal or command prompt.

Basic Extraction

The standard and recommended method for executing external processes in modern Python is subprocess.run(). Always pass the command and its arguments as a list to avoid shell injection vulnerabilities and parsing issues.

import subprocess

archive_path = "archive.rar"
destination_dir = "extracted_files/"

# 'x' extracts files with their original directory structure
command = ["unrar", "x", archive_path, destination_dir]

result = subprocess.run(command, capture_output=True, text=True)

if result.returncode == 0:
    print("Extraction successful.")
else:
    print(f"Extraction failed with error code {result.returncode}:")
    print(result.stderr)

Key Parameters Explained

  • capture_output=True: Captures both standard output (stdout) and standard error (stderr), preventing output from printing directly to the console.
  • text=True: Decodes stdout and stderr as strings rather than raw byte sequences.
  • Command Flag x vs e: The x command extracts files while preserving directory paths. If you want all files extracted into a single flat directory regardless of internal folder structures, replace x with e.

Overwriting Files and Running Silently

By default, unrar prompts for user input if a destination file already exists. To run the command unattended in an automated script, use standard unrar switches:

  • -y: Automatically answers "yes" to all queries (e.g., file overwrite confirmations).
  • -inul: Suppresses all error and normal console messages.
import subprocess

command = [
    "unrar",
    "x",
    "-y",  # Assume 'yes' on all prompts
    "archive.rar",
    "output_folder/"
]

result = subprocess.run(command, capture_output=True, text=True)

Extracting Password-Protected Archives

To extract an encrypted or password-protected archive, provide the -p switch directly followed by the password (no space between the flag and the password).

import subprocess

password = "SecretPassword123"
command = [
    "unrar",
    "x",
    "-y",
    f"-p{password}",
    "encrypted_archive.rar",
    "output_folder/"
]

result = subprocess.run(command, capture_output=True, text=True)

Robust Error Handling with check=True

Instead of manually inspecting result.returncode, pass check=True to raise a subprocess.CalledProcessError if unrar exits with a non-zero status code:

import subprocess

try:
    subprocess.run(
        ["unrar", "x", "-y", "missing_or_corrupt.rar", "output_folder/"],
        check=True,
        capture_output=True,
        text=True
    )
    print("Archive unpacked successfully.")
except subprocess.CalledProcessError as e:
    print(f"Command failed with exit code {e.returncode}")
    print(f"Error details: {e.stderr.strip()}")
except FileNotFoundError:
    print("Error: The 'unrar' binary was not found in the system PATH.")