To get the output of ls, use stdout=subprocess.PIPE.

>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo

The command cdrecord --help outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.

>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

As mentioned by Chris Morgan, you should be using proc.communicate() instead of proc.read().

>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout: 
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...
Answer from moinudin on Stack Overflow
Top answer
1 of 3
169

To get the output of ls, use stdout=subprocess.PIPE.

>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo

The command cdrecord --help outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.

>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

As mentioned by Chris Morgan, you should be using proc.communicate() instead of proc.read().

>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout: 
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...
2 of 3
49

If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output() command. Here is an example:

output = subprocess.check_output('ls')

To also redirect stderr you can use the following:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)
Discussions

python - saving subprocess output in a variable - Stack Overflow
I am using fping program to get network latencies of a list of hosts. Its a shell program but I want to use it in my python script and save the output in some database. I am using subprocess.call(... More on stackoverflow.com
🌐 stackoverflow.com
September 20, 2018
python - Retrieving the output of subprocess.call() - Stack Overflow
You now have the output of the command stored in the variable "output". "stdout = subprocess.PIPE" tells the class to create a file object named 'stdout' from within Popen. The communicate() method, from what I can tell, just acts as a convenient way to return a tuple of the output and the errors from the process you've run... More on stackoverflow.com
🌐 stackoverflow.com
February 1, 2012
Printing output from subprocess.run
That's because subprocess.check_output is it's own object not associated with the running process. subprocess.run returns a subprocess.CompletedProcess object. So you would use CompletedProcess.stdout to get the output. for x in allscripts: proc = subprocess.run([x], shell=True, capture_output=True) print(proc.stdout) Note: CompletedProcess.stdout returns bytes, so set text=True for raw text instead of bytes. You can also set stderr=sys.stdout to capture errors. More on reddit.com
🌐 r/learnpython
17
2
October 27, 2023
python - Redirect subprocess to a variable as a string - Stack Overflow
I was just typing out the same answer, but just wanted to say that I'd suggest using Popen rather than call because it's slightly more explicit and does the same thing. subprocess.call is just a convenience function for Popen. ... but call() prints the output and returns the exit code of your ... More on stackoverflow.com
🌐 stackoverflow.com
September 10, 2011
🌐
Python Forum
python-forum.io › thread-2392.html
[subprocess]>Run a cmd command and get output into a variable
Hello All, I'd like to run a windows cmd and get the result in a variable..it works well for a command but not for another... **confused** Here is : Command 'whoami' > Works !! **smile** [icode] import subprocess p1=subprocess.Popen(['whoami...
🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
2 weeks ago - Subclass of SubprocessError, raised when a timeout expires while waiting for a child process. ... Command that was used to spawn the child process. ... Timeout in seconds. ... Output of the child process if it was captured by run() or check_output(). Otherwise, None.
🌐
Medium
medium.com › @asvinjangid.kumar › how-to-store-the-output-of-a-command-in-a-variable-using-python-e7c1b8b91036
Store the Output of a Command in a Variable using Python. | by Ayush Sharma | Medium
January 7, 2024 - In this example, we use the `subprocess.check_output()` function to run the command `ls -l` and store its output in the `output` variable.
🌐
DataCamp
datacamp.com › tutorial › python-subprocess
An Introduction to Python Subprocess: Basics and Examples | DataCamp
September 12, 2025 - The command's return code will be stored in the return_code variable, which will be zero if the command was successful, and non-zero if it failed. subprocess.call() is useful when you want to run a command and check the return code, but do not need to capture the output.
Find elsewhere
🌐
GitHub
gist.github.com › nawatts › e2cdca610463200c12eac2a14efc0bfb
capture-and-print-subprocess-output.py · GitHub
The only way to accomplish this seems to be to start the subprocess with the non-blocking subprocess.Popen, poll for available output, and both print it and accumulate it in a variable.
🌐
Earthly
earthly.dev › blog › python-subprocess
How to Use Python's Subprocess Module - Earthly Blog
July 11, 2023 - The args attribute contains the arguments passed to the run() function. The returncode attribute indicates whether the command ran successfully; A return code of zero indicates successful execution. If the output of the command is captured, the stdout attribute contains the output; if we do not capture the output, stdout is None. In the subprocess module, the Popen class handles the creation and management of subprocesses.
🌐
Dataquest
dataquest.io › blog › python-subprocess
Python Subprocess: The Simple Beginner's Tutorial (2023)
February 19, 2025 - It's very helpful, and, in fact, it's the recommended option when you need to run multiple processes in parallel or call an external program or external command from inside your Python code. One of the pros of the subprocess module is that it allows the user to manage the inputs, the outputs, and even the errors raised by the child process from the Python code. This possibility makes calling subprocesses more powerful and flexible — it enables using the output of the subprocess as a variable throughout the rest of the Python script, for instance.
🌐
Reddit
reddit.com › r/learnpython › printing output from subprocess.run
r/learnpython on Reddit: Printing output from subprocess.run
October 27, 2023 -

I'm not getting an error but its not really printed what i wanted

I was trying to get these echo commands to show in either idle or running .py script

import subprocess

allscripts = ["./scripty1", "./scripty2", "./scripty3", "./scripty4", "./scripty5"]
for x in allscripts: subprocess.run([x], shell=True, capture_output=True) print(subprocess.check_output)

All it prints is this though

λ /bin/python /mnt/Stor2/Media/Share/DevShare/Py/InstallScript/InstallScript.py<function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040>

🌐
Digitaldesignjournal
digitaldesignjournal.com › python-subprocess-output-to-variable
Python Subprocess Output To Variable [Explained With Example]
September 24, 2023 - 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.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
How to get data from a variable into a subprocess.call command line - Raspberry Pi Forums
January 25, 2021 - So far, bls's suggestion works to get the variable values into the command string. However, the string doesn't work for some reason I'm trying to figure out now. ... import subprocess #Required to send picture and text mailMessage = "mailMsg" pictFile = "test" destPhone = "3165551212@vzwpix.com" print("Sending message...") cmd = 'mpack -s "{}" /media/{}.jpg {}' .format(mailMessage, pictFile, destPhone) print(cmd) subprocess.call(cmd) And this is the result: >>> %Run SendText.py Sending message...
🌐
Codecademy
codecademy.com › article › python-subprocess-tutorial-master-run-and-popen-commands-with-examples
Python Subprocess Tutorial: Master run() and Popen() Commands (with Examples) | Codecademy
It can also raise an exception if the command fails, capture output to variables, or run commands via the system shell. This function is ideal for short, one-off shell tasks without advanced interaction, such as installing dependencies, listing files, or automating routine jobs. ... subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)
🌐
Computer Science Atlas
csatlas.com › python-subprocess-run-stdout-stderr
Python 3: Get Standard Output and Standard Error from subprocess.run() — Computer Science Atlas
July 14, 2021 - from subprocess import run p = run( [ 'echo', 'hello' ], capture_output=True ) print( 'exit status:', p.returncode ) print( 'stdout:', p.stdout.decode() ) print( 'stderr:', p.stderr.decode() ) p.stdout and p.stderr are bytes (binary data), so if we want to use them as UTF-8 strings, we have to first .decode() them.