The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'โ€”you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

Answer from abarnert on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ subprocess.html
subprocess โ€” Subprocess management
1 week ago - Execute the string cmd in a shell with check_output() and return a 2-tuple (exitcode, output). encoding and errors are used to decode output; see the notes on Frequently Used Arguments for more details.
Top answer
1 of 4
112

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'โ€”you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

2 of 4
77

Since Python 3.5, subprocess.run is recommended instead of subprocess.check_output:

>>> subprocess.run(['cat','/tmp/text.txt'], check=True, stdout=subprocess.PIPE).stdout
b'First line\nSecond line\n'

Since Python 3.7, instead of the above, you can use capture_output=True parameter to capture stdout and stderr:

>>> subprocess.run(['cat','/tmp/text.txt'], check=True, capture_output=True).stdout
b'First line\nSecond line\n'

Also, you may want to use universal_newlines=True or its equivalent since Python 3.7 text=True to work with text instead of binary:

>>> stdout = subprocess.run(['cat', '/tmp/text.txt'], check=True, capture_output=True, text=True).stdout
>>> print(stdout)
First line
Second line
๐ŸŒ
Linux Hint
linuxhint.com โ€บ python-subprocess-check_output-method
How to Use Python Subprocess Check_output Method?
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-subprocess
An Introduction to Python Subprocess: Basics and Examples | DataCamp
September 12, 2025 - The subprocess.run() method takes several arguments, some of which are: args: The command to run and its arguments, passed as a list of strings. capture_output: When set to True, will capture the standard output and standard error. text: When set to True, will return the stdout and stderr as string, otherwise as bytes. check: a boolean value that indicates whether to check the return code of the subprocess, if check is true and the return code is non-zero, then subprocess CalledProcessError is raised.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python subprocess.check_output
Subprocess.check_output in Python | Delft Stack
October 10, 2023 - The subprocess.check_output() function will return the output of the given command as bytes. A CalledProcessError object is raised if the function returns a non-zero code. A CalledProcessError object has two attributes.
๐ŸŒ
OMZ Software
omz-software.com โ€บ editorial โ€บ docs โ€บ library โ€บ subprocess.html
17.1. subprocess โ€” Subprocess management โ€” Editorial Documentation
The full function signature is ... arguments are passed directly through to the Popen constructor. ... >>> subprocess.check_output(["echo", "Hello World!"]) 'Hello World!\n' >>> subprocess.check_output("exit 1", shell=True) Traceback (most recent call last): ...
๐ŸŒ
Read the Docs
stackless.readthedocs.io โ€บ en โ€บ 2.7-slp โ€บ library โ€บ subprocess.html
17.1. subprocess โ€” Subprocess management โ€” Stackless-Python 2.7.15 documentation
The full function signature is ... arguments are passed directly through to the Popen constructor. ... >>> subprocess.check_output(["echo", "Hello World!"]) 'Hello World!\n' >>> subprocess.check_output("exit 1", shell=True) Traceback (most recent call last): ...
Find elsewhere
๐ŸŒ
Housegordon
crashcourse.housegordon.org โ€บ python-subprocess.html
Python Subprocess Module - Running external programs - Crash Course By Assaf Gordon
#!/usr/bin/env python3 import signal from subprocess import check_output x = check_output("seq 1 0.0001 99999999 | head -n1", restore_signals=True,shell=True) print ("x = ", x)
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ subprocess
subprocess โ€“ Work with additional processes - Python Module of the Week
That means the calling programm cannot capture the output of the command. Use check_output() to capture the output for later processing. import subprocess output = subprocess.check_output(['ls', '-1']) print 'Have %d bytes in output' % len(output) print output
๐ŸŒ
Learn by Example
learnbyexample.github.io โ€บ tips โ€บ python-tip-11
Python tip 11: capture external command output
June 1, 2022 - >>> import subprocess >>> cmd = ('date', '-u', '+%A') >>> p = subprocess.run(cmd, capture_output=True, text=True) >>> p CompletedProcess(args=('date', '-u', '+%A'), returncode=0, stdout='Wednesday\n', stderr='') >>> p.stdout 'Wednesday\n' >>> subprocess.check_output(cmd, text=True) 'Wednesday\n'
๐ŸŒ
Stackify
stackify.com โ€บ a-guide-to-python-subprocess
A Guide to Python Subprocess - Stackify
January 21, 2025 - import subprocess # Simple output capture output = subprocess.check_output(['date']) print(f"Date output: '{output}'") # With error handling and timeout try: output = subprocess.check_output( ['curl', 'http://api.example.com'], timeout=5, text=True ...
๐ŸŒ
DataFlair
data-flair.training โ€บ blogs โ€บ python-subprocess-module
Python Subprocess Module | Subprocess vs Multiprocessing - DataFlair
March 8, 2021 - Traceback (most recent call last): File โ€œ<pyshell#3>โ€, line 1, in <module> subprocess.check_call(โ€˜trueโ€™,shell=True) File โ€œC:\Users\Ayushi\AppData\Local\Programs\Python\Python37-32\lib\subprocess.pyโ€, line 328, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command โ€˜trueโ€™ returned non-zero exit status 1.For the false command, it always returns an error. This function runs the command with the arguments and returns the output.
๐ŸŒ
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>

๐ŸŒ
Python Geeks
pythongeeks.org โ€บ python geeks โ€บ learn python โ€บ subprocess in python
Subprocess in Python - Python Geeks
August 25, 2021 - 3. We give the value of the standard output stream to the stout parameter ยท 4. stderr is used to handle errors, if any, that occurred from the standard error stream ยท 5. shell is the boolean value. If it is true then the program executes in a new shell. ... CalledProcessError Traceback (most recent call last) <ipython-input-15-66ab34d0619e> in <module> 1 import subprocess 2 โ€”-> 3 subprocess.check_call(โ€˜Falseโ€™,shell=True)~\anaconda3\lib\subprocess.py in check_call(*popenargs, **kwargs) 362 if cmd is None: 363 cmd = popenargs[0] โ€“> 364 raise CalledProcessError(retcode, cmd) 365 return 0 366CalledProcessError: Command โ€˜Falseโ€™ returned non-zero exit status 1.
๐ŸŒ
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.
๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ python subprocess: master external command execution
Python Subprocess: Master External Command Execution
December 15, 2025 - Learn about Python's subprocess module for executing external commands. Discover how to manage processes and handle inputs/outputs efficiently.
Address ย  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-subprocess-module
Python subprocess module - GeeksforGeeks
August 21, 2024 - ... import subprocess try: ans = subprocess.check_output(["python", "--version"], text=True) print(ans) except subprocess.CalledProcessError as e: print(f"Command failed with return code {e.returncode}")