Python Subprocess Output To Variable [Explained With Example]

You can use the subprocess module to run external commands and capture their output in a variable. Here’s how you can do it with an example:

Let’s say you want to run the ls command (which lists files and directories in a directory) and capture its output in a variable.

import subprocess

# Run the 'ls' command and capture its output
result = subprocess.run(['ls'], stdout=subprocess.PIPE, text=True)

# Extract the output from the result object
output = result.stdout

# Print the captured output
print(output)
Code language: Python (python)

In this example:

  1. We import the subprocess module.
  2. We use subprocess.run() to run the ls command. We pass the command as a list of strings, where each element is a part of the command. We also specify stdout=subprocess.PIPE to capture the standard output of the command, and text=True to indicate that we want the output as a text (string) rather than bytes.
  3. The result of subprocess.run() is stored in the result variable, which contains information about the command execution.
  4. We extract the standard output of the command from the result object using result.stdout.
  5. Finally, we print the captured output.

You can replace the 'ls' command with any other command you want to run. Just provide the command and its arguments as a list of strings to subprocess.run(), and you can capture the output in a variable for further processing in your Python script.

Redirect Subprocess To A Variable As A String

To redirect the output of a subprocess to a variable as a string, you can use the subprocess.Popen class along with communicate() to capture both the standard output and standard error of the subprocess. Here’s an example:

import subprocess

# Define the command as a list of strings
command = ['ls', '-l']

# Run the command and capture its output
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()

# Check if there was an error while running the command
if process.returncode != 0:
    print(f"Error executing the command: {stderr}")
else:
    # Capture the standard output as a string
    output = stdout.strip()
    print(output)Code language: Python (python)

In this example:

  1. We use the subprocess.Popen class to run the ls -l command. We specify stdout=subprocess.PIPE and stderr=subprocess.PIPE to capture both the standard output and standard error of the subprocess. Additionally, we set text=True to ensure the output is returned as text (string).
  2. We use process.communicate() to start the command and capture its output. This method returns a tuple containing the standard output and standard error as strings.
  3. We check the returncode attribute of the process object to see if the command executed successfully (a return code of 0 indicates success). If there was an error, we print the standard error message.
  4. If the command executed successfully, we capture the standard output as a string by stripping any leading or trailing whitespace and then print it.

This way, you can run a subprocess and capture its output as a string in the output variable.

Capturing output from subprocess.run()

You can capture the output from subprocess.run() by accessing the stdout attribute of the CompletedProcess object returned by the function. Here’s how you can do it:

import subprocess

# Define the command as a list of strings
command = ['ls', '-l']

# Run the command and capture its output
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# Check if there was an error while running the command
if result.returncode != 0:
    print(f"Error executing the command: {result.stderr}")
else:
    # Capture the standard output as a string
    output = result.stdout.strip()
    print(output)
Code language: Python (python)

In this example:

  1. We use subprocess.run() to run the ls -l command. We specify stdout=subprocess.PIPE and stderr=subprocess.PIPE to capture both the standard output and standard error of the subprocess. Additionally, we set text=True to ensure the output is returned as text (string).
  2. The result of subprocess.run() is stored in the result variable, which is a CompletedProcess object containing information about the command execution.
  3. We check the returncode attribute of the result object to see if the command executed successfully (a return code of 0 indicates success). If there was an error, we print the standard error message.
  4. If the command executed successfully, we capture the standard output as a string by stripping any leading or trailing whitespace and then print it.

This way, you can run a subprocess and capture its output as a string using subprocess.run() and the stdout attribute of the result.

Read More;

  • Aniket Singh

    Aniket Singh holds a B.Tech in Computer Science & Engineering from Oriental University. He is a skilled programmer with a strong coding background, having hands-on experience in developing advanced projects, particularly in Python and the Django framework. Aniket has worked on various real-world industry projects and has a solid command of Python, Django, REST API, PostgreSQL, as well as proficiency in C and C++. He is eager to collaborate with experienced professionals to further enhance his skills.

    View all posts

Leave a Comment