In all officially maintained versions of Python, the simplest approach is to use the subprocess.check_output function:

>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

check_output runs a single program that takes only arguments as input.1 It returns the result exactly as printed to stdout. If you need to write input to stdin, skip ahead to the run or Popen sections. If you want to execute complex shell commands, see the note on shell=True at the end of this answer.

The check_output function works in all officially maintained versions of Python. But for more recent versions, a more flexible approach is available.

Modern versions of Python (3.5 or higher): run

If you're using Python 3.5+, and do not need backwards compatibility, the new run function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the subprocess module. To capture the output of a program, pass the subprocess.PIPE flag to the stdout keyword argument. Then access the stdout attribute of the returned CompletedProcess object:

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

The return value is a bytes object, so if you want a proper string, you'll need to decode it. Assuming the called process returns a UTF-8-encoded string:

>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

This can all be compressed to a one-liner if desired:

>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

If you want to pass input to the process's stdin, you can pass a bytes object to the input keyword argument:

>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'

You can capture errors by passing stderr=subprocess.PIPE (capture to result.stderr) or stderr=subprocess.STDOUT (capture to result.stdout along with regular output). If you want run to throw an exception when the process returns a nonzero exit code, you can pass check=True. (Or you can check the returncode attribute of result above.) When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.

Later versions of Python streamline the above further. In Python 3.7+, the above one-liner can be spelled like this:

>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Using run this way adds just a bit of complexity, compared to the old way of doing things. But now you can do almost anything you need to do with the run function alone.

Older versions of Python (3-3.4): more about check_output

If you are using an older version of Python, or need modest backwards compatibility, you can use the check_output function as briefly described above. It has been available since Python 2.7.

subprocess.check_output(*popenargs, **kwargs)  

It takes takes the same arguments as Popen (see below), and returns a string containing the program's output. The beginning of this answer has a more detailed usage example. In Python 3.5+, check_output is equivalent to executing run with check=True and stdout=PIPE, and returning just the stdout attribute.

You can pass stderr=subprocess.STDOUT to ensure that error messages are included in the returned output. When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.

If you need to pipe from stderr or pass input to the process, check_output won't be up to the task. See the Popen examples below in that case.

Complex applications and legacy versions of Python (2.6 and below): Popen

If you need deep backwards compatibility, or if you need more sophisticated functionality than check_output or run provide, you'll have to work directly with Popen objects, which encapsulate the low-level API for subprocesses.

The Popen constructor accepts either a single command without arguments, or a list containing a command as its first item, followed by any number of arguments, each as a separate item in the list. shlex.split can help parse strings into appropriately formatted lists. Popen objects also accept a host of different arguments for process IO management and low-level configuration.

To send input and capture output, communicate is almost always the preferred method. As in:

output = subprocess.Popen(["mycmd", "myarg"], 
                          stdout=subprocess.PIPE).communicate()[0]

Or

>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, 
...                                    stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo

If you set stdin=PIPE, communicate also allows you to pass data to the process via stdin:

>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
...                           stderr=subprocess.PIPE,
...                           stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo

Note Aaron Hall's answer, which indicates that on some systems, you may need to set stdout, stderr, and stdin all to PIPE (or DEVNULL) to get communicate to work at all.

In some rare cases, you may need complex, real-time output capturing. Vartec's answer suggests a way forward, but methods other than communicate are prone to deadlocks if not used carefully.

As with all the above functions, when security is not a concern, you can run more complex shell commands by passing shell=True.

Notes

1. Running shell commands: the shell=True argument

Normally, each call to run, check_output, or the Popen constructor executes a single program. That means no fancy bash-style pipes. If you want to run complex shell commands, you can pass shell=True, which all three functions support. For example:

>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376\n'

However, doing this raises security concerns. If you're doing anything more than light scripting, you might be better off calling each process separately, and passing the output from each as an input to the next, via

run(cmd, [stdout=etc...], input=other_output)

Or

Popen(cmd, [stdout=etc...]).communicate(other_output)

The temptation to directly connect pipes is strong; resist it. Otherwise, you'll likely see deadlocks or have to do hacky things like this.

Answer from senderle on Stack Overflow
Top answer
1 of 16
1971

In all officially maintained versions of Python, the simplest approach is to use the subprocess.check_output function:

>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

check_output runs a single program that takes only arguments as input.1 It returns the result exactly as printed to stdout. If you need to write input to stdin, skip ahead to the run or Popen sections. If you want to execute complex shell commands, see the note on shell=True at the end of this answer.

The check_output function works in all officially maintained versions of Python. But for more recent versions, a more flexible approach is available.

Modern versions of Python (3.5 or higher): run

If you're using Python 3.5+, and do not need backwards compatibility, the new run function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the subprocess module. To capture the output of a program, pass the subprocess.PIPE flag to the stdout keyword argument. Then access the stdout attribute of the returned CompletedProcess object:

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

The return value is a bytes object, so if you want a proper string, you'll need to decode it. Assuming the called process returns a UTF-8-encoded string:

>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

This can all be compressed to a one-liner if desired:

>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

If you want to pass input to the process's stdin, you can pass a bytes object to the input keyword argument:

>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'

You can capture errors by passing stderr=subprocess.PIPE (capture to result.stderr) or stderr=subprocess.STDOUT (capture to result.stdout along with regular output). If you want run to throw an exception when the process returns a nonzero exit code, you can pass check=True. (Or you can check the returncode attribute of result above.) When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.

Later versions of Python streamline the above further. In Python 3.7+, the above one-liner can be spelled like this:

>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Using run this way adds just a bit of complexity, compared to the old way of doing things. But now you can do almost anything you need to do with the run function alone.

Older versions of Python (3-3.4): more about check_output

If you are using an older version of Python, or need modest backwards compatibility, you can use the check_output function as briefly described above. It has been available since Python 2.7.

subprocess.check_output(*popenargs, **kwargs)  

It takes takes the same arguments as Popen (see below), and returns a string containing the program's output. The beginning of this answer has a more detailed usage example. In Python 3.5+, check_output is equivalent to executing run with check=True and stdout=PIPE, and returning just the stdout attribute.

You can pass stderr=subprocess.STDOUT to ensure that error messages are included in the returned output. When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.

If you need to pipe from stderr or pass input to the process, check_output won't be up to the task. See the Popen examples below in that case.

Complex applications and legacy versions of Python (2.6 and below): Popen

If you need deep backwards compatibility, or if you need more sophisticated functionality than check_output or run provide, you'll have to work directly with Popen objects, which encapsulate the low-level API for subprocesses.

The Popen constructor accepts either a single command without arguments, or a list containing a command as its first item, followed by any number of arguments, each as a separate item in the list. shlex.split can help parse strings into appropriately formatted lists. Popen objects also accept a host of different arguments for process IO management and low-level configuration.

To send input and capture output, communicate is almost always the preferred method. As in:

output = subprocess.Popen(["mycmd", "myarg"], 
                          stdout=subprocess.PIPE).communicate()[0]

Or

>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, 
...                                    stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo

If you set stdin=PIPE, communicate also allows you to pass data to the process via stdin:

>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
...                           stderr=subprocess.PIPE,
...                           stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo

Note Aaron Hall's answer, which indicates that on some systems, you may need to set stdout, stderr, and stdin all to PIPE (or DEVNULL) to get communicate to work at all.

In some rare cases, you may need complex, real-time output capturing. Vartec's answer suggests a way forward, but methods other than communicate are prone to deadlocks if not used carefully.

As with all the above functions, when security is not a concern, you can run more complex shell commands by passing shell=True.

Notes

1. Running shell commands: the shell=True argument

Normally, each call to run, check_output, or the Popen constructor executes a single program. That means no fancy bash-style pipes. If you want to run complex shell commands, you can pass shell=True, which all three functions support. For example:

>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376\n'

However, doing this raises security concerns. If you're doing anything more than light scripting, you might be better off calling each process separately, and passing the output from each as an input to the next, via

run(cmd, [stdout=etc...], input=other_output)

Or

Popen(cmd, [stdout=etc...]).communicate(other_output)

The temptation to directly connect pipes is strong; resist it. Otherwise, you'll likely see deadlocks or have to do hacky things like this.

2 of 16
208

This is way easier, but only works on Unix (including Cygwin) and Python2.7.

import commands
print commands.getstatusoutput('wc -l file')

It returns a tuple with the (return_value, output).

For a solution that works in both Python2 and Python3, use the subprocess module instead:

from subprocess import Popen, PIPE
output = Popen(["date"],stdout=PIPE)
response = output.communicate()
print response
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python running shell command and capturing the output
Python Running Shell Command and Capturing the Output - Spark By {Examples}
June 25, 2024 - You can do this using pip: ... import sh # Define the shell command you want to run cmd = "ls -l" # Run the command and capture the output output = sh.ls("-l") # Print the captured output print(output)
Discussions

Immediate output via command line?
Well, you can call sys.stdout.flush() to dump the buffer (you can call flush() on any buffered IO, in fact.) Ideally, I would like to be able to clear the screen and place/erase text at x,y coordinates Then you need whatever the Win10 equivalent of curses is. More on reddit.com
🌐 r/learnpython
5
1
December 5, 2022
How to send commands to Windows command line with Python?
Sounds like something that should just be a batch file. More on reddit.com
🌐 r/learnpython
14
3
November 4, 2020
Capturing output from subprocess.run()

You’ll need to use the stdout and/or stderr arguments. https://docs.python.org/3/library/subprocess.html#subprocess.run

Edit: link to #subprocess.run

More on reddit.com
🌐 r/learnpython
5
7
January 29, 2018
How to run remote shell commands and save the output to a variable
Assuming the client is Paramiko, the answers to this SO question explain that you have to do something extra to wait for the command to finish. More on reddit.com
🌐 r/learnpython
4
1
June 22, 2022
🌐
Medium
medium.com › @prasadaniroodh › capturing-command-output-in-python-simplifying-system-interactions-b490c0a7139f
Capturing Command Output in Python: Simplifying System Interactions. | by Aniroodh Prasad | Medium
July 24, 2023 - With the command defined, we can now run it using the subprocess.run() function. By setting capture_output=True, we instruct Python to capture the output of the command.
🌐
nixCraft
cyberciti.biz › nixcraft › howto › python › python run external command and get output on screen or in variable
Python Run External Command And Get Output On Screen or In Variable - nixCraft
March 28, 2023 - It will block next statement till external command is completed i.e. you will not get real time output from the command. The following program will run netstat unix command and start display output immediately on screen: #!/usr/bin/python import subprocess, sys ## command to run - tcp only ## cmd = "/usr/sbin/netstat -p tcp -f inet" ## run it ## p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE) ## But do not wait till netstat finish, start displaying output immediately ## while True: out = p.stderr.read(1) if out == '' and p.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush()
🌐
GeeksforGeeks
geeksforgeeks.org › python › print-output-from-os-system-in-python
Print Output from Os.System in Python - GeeksforGeeks
July 23, 2025 - This way, you can catch and handle errors gracefully in case the executed command fails. ... import subprocess command = "ls" try: result = subprocess.check_output(command, shell=True, text=True) print(result) except subprocess.CalledProcessError as e: print(f"Error executing command: {e}") ... Example 1: In this Python example, the os.system function is used to run a simple command (echo Hello, World!).
🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
1 week ago - Like getstatusoutput(), except the exit code is ignored and the return value is a string containing the command’s output. Example: ... Availability: Unix, Windows. ... Changed in version 3.11: Added the encoding and errors parameters. When using the timeout parameter in functions like run(), ...
🌐
Medium
medium.com › @amarjeetaryan90 › python-command-output-capture-a-comprehensive-tutorial-on-storing-output-as-variables-c578cb900c2
Python Command Output Capture: A Comprehensive Tutorial on Storing Output as Variables | by Amarjeet Aryan | Medium
July 1, 2023 - Step 2: Executing the Command and Capturing the Output To execute the desired command and capture its output, use the `subprocess.check_output()` function. Replace `”your-command”` with the actual command you want to run.
Find elsewhere
🌐
Python Forum
python-forum.io › thread-34738.html
Command output to Variable
August 26, 2021 - Good afternoon everyone. I am new to python and I am trying to get my self up to speed as soon as possible. I thought it would be easy since ive already worked with VBS and Powershell but this seems like a whole new animal. so what I am trying to do ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-system-command-os-subprocess-call
Python os.system() vs subprocess: Run System Commands | DigitalOcean
1 month ago - Python’s subprocess module gives you full control over running system commands, from simple one-liners to complex pipelines with real-time output streaming. For new projects, use subprocess.run() as your default. It handles output capture, error checking, and timeouts in a single function call.
🌐
w3resource
w3resource.com › python-exercises › python-basic-exercise-102.php
Python: Get system command output - w3resource
May 17, 2025 - returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True) # Print a message indicating the purpose of running the 'dir' command. print("dir command to list files and directories") # Print the output (list of files and directories) returned by the 'dir' command.
🌐
Quora
quora.com › What-is-a-convenient-way-to-execute-a-shell-command-in-Python-and-retrieve-its-output
What is a convenient way to execute a shell command in Python and retrieve its output? - Quora
So if yu create a string which ... of an executed command so you can use it for various purposes, then you can use the subprocess module....
🌐
Delft Stack
delftstack.com › home › howto › python › python execute shell command and get output
How to Execute Shell Command and Get Output in Python | Delft Stack
February 2, 2024 - In this article, we will learn how to execute cmd commands from a Python script with the help of os.system(). We will also learn how we can execute cmd commands from the script in an easier way with the help of the subprocess module in Python.
🌐
Arch Linux Forums
bbs.archlinux.org › viewtopic.php
Python3: get stdout of a command in real time / Programming & Scripting / Arch Linux Forums
December 21, 2023 - That example code runs another program and captures it's output. You say that example code works with ping, but not with other programs. So that must mean your example code works, and your problem is actually those "other" programs. Are they written in Python also, so are you really asking about them?
🌐
Python Module of the Week
pymotw.com › 2 › commands
commands – Run external shell commands - Python Module of the Week
If the exit code is not useful for your application, you can use getoutput() to receive only the text output from the command. from commands import * text = getoutput('ls -l *.py') print 'ls -l *.py:' print text print text = getoutput('ls -l *.notthere') print 'ls -l *.py:' print text · $ ...
🌐
DataCamp
datacamp.com › tutorial › python-subprocess
An Introduction to Python Subprocess: Basics and Examples | DataCamp
September 12, 2025 - Using the Python subprocess module ... programs with your Python code. For example, you can use the subprocess module to run a shell command, like ls or ping, and get the output of that command in your Python code....
🌐
iO Flood
ioflood.com › blog › python-run-shell-command
Using Python to Run Shell Commands
December 7, 2023 - import subprocess result = subprocess.run('ls -l | grep .py', shell=True) # Output: # [Expected output from the ls -l | grep .py command] In this example, we’re using a pipe (|) to combine two shell commands. This is not possible when passing the command as a list of strings, so we use shell=True to pass the command as a string instead. As we can see, the subprocess module is a powerful tool for running shell commands in Python. It provides a high level of control over how commands are run and how their output is handled, making it a great choice for both simple and complex tasks.
🌐
Medium
medium.com › @anshulgarwal45 › how-to-store-the-output-of-a-command-using-python-f54b28ce256
How to Store the Output of a Command Using Python | by Anshul Garwal | Medium
July 1, 2023 - The subprocess module in Python allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. You can leverage this module to execute system commands and store their output.
🌐
Janakiev
janakiev.com › blog › python-shell-commands
How to Execute Shell Commands with Python - njanakiev
April 22, 2019 - But what usually will end up in ... done in Python. You’ll learn here how to do just that with the os and subprocess modules. The first and the most straight forward approach to run a shell command is by using os.system(): ... If you save this as a script and run it, you will see the output in the command line. The problem with this approach is in its inflexibility since you can’t even get the resulting ...