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
The following contrived example runs base64 with STDIN redirected from a file (in real-world applications it is recommended to use python’s built-in base64 module): # shell equivalent: # b=$(base64 < /etc/passwd) || echo base64 failed · from subprocess import check_output import sys try: fin=open('/etc/passwd','r') b=check_output(["base64"], stdin=fin) fin.close() print ("encoded passwd: %s" % str(b)) except IOError as e: sys.exit("I/O error on '%s': %s" % (e.filename, e.strerror)) except CalledProcessError as e: sys.exit("base64 failed: %s" % (str(e))) except OSError as e: sys.exit("failed to run 'base64': %s" % (str(e)))
🌐
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 - For example: import subprocess def get_system_info(): """ Collect various system information using system commands. """ info = {} commands = { 'cpu': ['lscpu'], 'memory': ['free', '-h'], 'disk': ['df', '-h'], 'network': ['ifconfig'], 'processes': ['ps', 'aux'] } for key, command in commands.items(): try: output = subprocess.check_output( command, text=True, timeout=10 ) info[key] = output.strip() except Exception as e: info[key] = f"Error: {str(e)}" return info # Example usage system_info = get_system_info() for category, data in system_info.items(): print(f"\n=== {category.upper()} ===") print(data) Using shell=True can introduce several security risks: Command injection vulnerabilities ·
🌐
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>

🌐
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
🌐
Real Python
realpython.com › python-subprocess
The subprocess Module: Wrapping Programs With Python – Real Python
January 18, 2025 - Note: If you’re trying to decide whether you need subprocess or not, check out the section on deciding whether you need subprocess for your task. You may come across other functions like call(), check_call(), and check_output(), but these belong to the older subprocess API from Python 3.5 and earlier.
🌐
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.
🌐
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}")