Try something like this:

import subprocess
file_ = open("ouput.txt", "w")
subprocess.Popen("ls", stdout=file_)

EDIT: Matching your needs

import subprocess

file_ = open("ouput.txt", "w")
subprocess.Popen(["host", ipAddress], stdout=file_)
Answer from Raydel Miranda on Stack Overflow
๐ŸŒ
Quora
quora.com โ€บ How-do-I-save-a-shell-output-to-a-file-in-Python
How to save a shell output to a file in Python - Quora
ยท ยท The simplest approach is to use the subprocess.check_output function: ... 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.
Discussions

python - writing command line output to file - Stack Overflow
I am writing a script to clean up my desktop, moving files based on file type. The first step, it would seem, is to ls -1 /Users/user/Desktop (I'm on Mac OSX). So, using Python, how would I run a c... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Running Python script using shell script redirecting python output - Unix & Linux Stack Exchange
The line $COMMAND >> py.log & causes the python process to run in the background and so the script will immediately proceed to writelog "Exited with status $?", probably before the python process has exited. This is not the intended behavior I think. ... I ended up using the module redirect_stdout to redirect output to a file and then using sys.stdout.flush() after each print() and for the shell ... More on unix.stackexchange.com
๐ŸŒ unix.stackexchange.com
March 9, 2020
How to execute a python script and write output to txt file? - Stack Overflow
I'm executing a .py file, which spits out a give string. This command works fine execfile ('file.py') But I want the output (in addition to it being shown in the shell) written into a text file. I... More on stackoverflow.com
๐ŸŒ stackoverflow.com
linux - How to execute a python script and write output to a file? - Stack Overflow
i have the following script in python with a while loop from time import sleep while True: print "hola" print "mundo" sleep(2) and i want to write the output to a file ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
๐ŸŒ
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 - In our case, we pass shell=True to enable shell execution and text=True to ensure that the output is returned as a string. The output of the command is stored in the output variable, which can be further processed or stored as needed.
๐ŸŒ
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 - Executing shell commands with Python often involves passing strings to the subprocess module. If you construct these strings improperly, you might inadvertently expose your code to command injection vulnerabilities. Command injection occurs when an attacker manipulates the input to include malicious commands. import subprocess filename = "file.txt" command = f"cat {filename}" output = subprocess.check_output(command, shell=True)
Find elsewhere
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ executing-shell-commands-with-python
Executing Shell Commands with Python
January 6, 2023 - Now let's try to use one of the more advanced features of subprocess.run(), namely ignore output to stdout. In the same list_subprocess.py file, change: ... The standard output of the command now pipes to the special /dev/null device, which means the output would not appear on our consoles. Execute the file in your shell to see the following output:
๐ŸŒ
Stack Exchange
unix.stackexchange.com โ€บ questions โ€บ 572048 โ€บ running-python-script-using-shell-script-redirecting-python-output
Running Python script using shell script redirecting python output - Unix & Linux Stack Exchange
March 9, 2020 - The line $COMMAND >> py.log & causes the python process to run in the background and so the script will immediately proceed to writelog "Exited with status $?", probably before the python process has exited. This is not the intended behavior I think. ... I ended up using the module redirect_stdout to redirect output to a file and then using sys.stdout.flush() after each print() and for the shell script COMMAND='./test.py run'.
๐ŸŒ
Martin Heinz
martinheinz.dev โ€บ blog โ€บ 98
The Right Way to Run Shell Commands From Python | Martin Heinz | Personal Website & Blog
June 5, 2023 - If the command is not in $PATH, ... So simple and straight-forward, right? To write output of a command to a file you only need to provide _out argument to the function:...
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-35153.html
Showing and saving the output of a python file run through bash
Hi all, I'm new to the world of Python, linux and programming in general so my question may be very basic but I can't find an answer anywhere. I'm running a python file (to do a regression so I'm expecting tables as result) on a virtual cluster usi...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to run remote shell commands and save the output to a variable
r/learnpython on Reddit: How to run remote shell commands and save the output to a variable
June 22, 2022 -

I currently have this function which I can pass IPs into and it will display what I want. The issue is I am trying to take the output and perform a conditional against it. I feel like there is something simple I am missing here, but I can't seem to figure it out. Note: That print statement works, I just cannot get it into a variable (Always ends up empty it seems)

def linuxConnect(ip):
    client.connect(hostname=ip, username=linuxUname, password=linuxPwd)
    stdin, stdout, stderr = client.exec_command('nginx -v')
    print(stdout.read().decode())
    err = stderr.read().decode()
    if err:
        print(err)
    client.close()
    return
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ print-output-from-os-system-in-python
Print Output from Os.System in Python - GeeksforGeeks
April 28, 2025 - Example 2: In this Python example, the os.system function is used to run a command (ls -l to list files in the current directory). The exit code of the command is captured, and it is printed to the console.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ subprocess.html
subprocess โ€” Subprocess management
1 week ago - Return output (stdout and stderr) of executing cmd in a shell. 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(), Popen.wait(), or Popen.communicate(), users should be aware of the following behaviors:
๐ŸŒ
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 - #!/usr/bin/python ## get subprocess module import subprocess ## call date command ## p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True) ## Talk with date command i.e. read data from stdout and stderr. Store this info in tuple ## ## Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.