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 - With check_output(), you'll get an exception if something goes wrong with the command being executed. With run(), you'll get that information from stderr and returncode as part of the CompletedProcess object. >>> cmd = ('ls', 'xyz.txt') >>> subprocess.run(cmd, capture_output=True, text=True) ...
๐ŸŒ
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.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ subprocess module in python
Subprocess Module in Python| Scaler Topics
November 3, 2022 - Return Value: The Python subprocess.check_output() function generally returns the same output as the subprocess call(). It outputs the executed code of the program. But in case there is no program output, then the function returns the code itself ...
๐ŸŒ
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}")