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 - Return (exitcode, output) of executing cmd in a shell. Execute the string cmd in a shell with check_output() and return a 2-tuple (exitcode, output).
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
Discussions

Printing output from subprocess.run
That's because subprocess.check_output is it's own object not associated with the running process. subprocess.run returns a subprocess.CompletedProcess object. So you would use CompletedProcess.stdout to get the output. for x in allscripts: proc = subprocess.run([x], shell=True, capture_output=True) print(proc.stdout) Note: CompletedProcess.stdout returns bytes, so set text=True for raw text instead of bytes. You can also set stderr=sys.stdout to capture errors. More on reddit.com
🌐 r/learnpython
17
2
October 27, 2023
[Help] Getting blank string from subprocess.check_output

I remember having some similar issues. I checked my notes and I wound up doing it like this.

cmd = 'echo Some command string'
result = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = result.stdout.decode('utf-8')
stderr = result.stderr.decode('utf-8')
status = 'COMPLETE' if result.returncode == 0 else 'FAILED'
More on reddit.com
🌐 r/learnpython
4
1
March 24, 2020
Rhino8 python subprocess.check_output() error
Hi There, In rhino7 I was used ... the PYTHONHOME variable judging by this post. To me it seems that Rhino8 has set the PYTHONHOME variable and I need to make sure that the check_output() call does not use this variable Does anyone know how to solve this issue? Thanks, Tim ... More on discourse.mcneel.com
🌐 discourse.mcneel.com
1
0
December 12, 2023
subprocess.check_output(shell=True) handle non-zero exit status codes
My question is how do I handle non-zero exit status using subprocess.check_output() The reason it's called "check_output" is because that's what it's checking - that the exit status of the subprocess is zero. If it isn't, it raises subprocess.CalledProcessError. If you don't care that the exit code is non-zero, then don't run it with check_output. (Anyway you should be using subprocess.run for everything, these days.) Alternatively, catch and respond to the CalledProcessError. More on reddit.com
🌐 r/learnpython
3
1
January 26, 2021
🌐
DataCamp
datacamp.com › tutorial › python-subprocess
An Introduction to Python Subprocess: Basics and Examples | DataCamp
September 12, 2025 - You can also use it to run other Python scripts or executables, like .exe files on Windows. Additionally, the subprocess module can redirect the input and output of the process, meaning you can control what data is sent to the process and what data is received from it. One of the most useful capabilities of the subprocess module is that it enables the user to handle the inputs, outputs, and errors (usually on stderr) generated by the child process. With check=True, a CalledProcessError is raised and you can inspect e.stdout/e.stderr.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-subprocess-module
Python subprocess module - GeeksforGeeks
2 weeks ago - The subprocess module is used to run external programs or system commands from Python. It allows to execute commands, capture their output and interact with other processes. One can also send input, handle errors and check execution status.
🌐
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>

🌐
Readthedocs
pydoc-zh.readthedocs.io › en › latest › library › subprocess.html
17.1. subprocess — Subprocess management — Python 2.7.6 documentation
The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute. The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the slightly odd notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor, except that stdout is not permitted as it is used internally. All other supplied 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
🌐
Real Python
realpython.com › ref › stdlib › subprocess
subprocess | Python Standard Library – Real Python
It’s a powerful tool for running and controlling external programs within a Python script. ... >>> import subprocess >>> result = subprocess.run( ... ["echo", "Hello, World!"], capture_output=True, text=True ...
🌐
Stackify
stackify.com › a-guide-to-python-subprocess
A Guide to Python Subprocess - Stackify
January 21, 2025 - import subprocess # Simple command execution result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print(result.stdout) # With additional parameters result = subprocess.run( ['python', 'script.py'], capture_output=True, text=True, timeout=60, check=True ) print(result.stdout) The run() function offers several useful parameters: capture_output: Captures stdout and stderr ·
🌐
Housegordon
crashcourse.housegordon.org › python-subprocess.html
Python Subprocess Module - Running external programs - Crash Course By Assaf Gordon
#!/usr/bin/env python from subprocess import check_output x = check_output("seq 1 0.0001 99999999 | head -n1",shell=True)
🌐
GeeksforGeeks
geeksforgeeks.org › python › retrieving-the-output-of-subprocesscall-in-python
Retrieving the output of subprocess.call() in Python - GeeksforGeeks
July 23, 2025 - Here’s how to use subprocess.check_output(): This function: Captures and returns the standard output of the command. Raises an exception if the command fails (non-zero exit status). Python ·
🌐
Reddit
reddit.com › r/learnpython › [help] getting blank string from subprocess.check_output
r/learnpython on Reddit: [Help] Getting blank string from subprocess.check_output
March 24, 2020 -

I posted about a day ago about this issue, but I have dug further since then. The issue is that I am trying to write a grader for student python code, so I execute their code by system command, and direct that output to a file. When I run the program from my IDE (PyCharm) it works perfectly. When I run it from the windows command line or from a batch file, I just get an empty string from the command running the student file.

I used to be using

os.system(f'python "{script_name}" > "{out_file}" 2>&1')

but have upgraded to using

f.write(subprocess.check_output(['python', script_name], stderr=subprocess.STDOUT, shell=True).decode('utf-8'))

I'm just getting an empty string when using subprocess.check_output and when using os.system a blank output file would be created every time. I have unit tested the issue using

print('test:', subprocess.check_output(['echo', 'test_phrase'], shell=True).decode('utf-8'))

which works fine from IDE, command line, or a batch file so long as shell=True is specified. Putting shell=True seems to have no effect on my actual use case.

I found someone else who seems to have my same problem, but they got no reply. I also found this similar issue on stack overflow, but it looks like their issue was something with activating the conda environment. I have tried the system 3.7 interpreter and my virtual env for the project, no difference. The folders I'm dealing with are just in my user directory and there should be no weird permission issues.

Any ideas on why I can't get any output unless I run from PyCharm would be great. The code is here and the issue is in run_file from FileExecution.execute.py if you care to look at the actual project.

🌐
Python
bugs.python.org › issue40497
Issue 40497: subprocess.check_output() accept the check keyword argument - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/84677
🌐
GitHub
gist.github.com › 839684
[Python] subprocess.check_output() for Python < 2.7 · GitHub
[Python] subprocess.check_output() for Python < 2.7 · Raw · subprocess_check_output.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Real Python
realpython.com › python-subprocess
The subprocess Module: Wrapping Programs With Python – Real Python
January 18, 2025 - Sometimes the child process inherits these streams from the parent. This is what’s happening when you use subprocess.run() in the REPL and are able to see the output of the command. The stdout of the Python interpreter is inherited by the subprocess.
🌐
Reddit
reddit.com › r/learnpython › subprocess.check_output(shell=true) handle non-zero exit status codes
r/learnpython on Reddit: subprocess.check_output(shell=True) handle non-zero exit status codes
January 26, 2021 -

Working on a practice project that requires command line access over a client initiated ssh session. I have ssh working with paramiko. The client is able to log into the ssh server (code snippets below). When the client connects and the session is open, it sends 'Command Shell Open' via chan.send and goes into a while loop. chan.recv().decode() is used to receive commands from the server side across the ssh tunnel. subprocess.check_output(shell=True) is used to execute the command locally. The output of the command is then sent back to the server using chan.send(). This all works great for commands like ls,dir,pwd,ps ..etc. Commands that return a zero exit status during the subprocess.check_output(shell=True) step (I assume). When I issue a command that returns a non-zero exit status, ping for example I get this error message on the client and the client script stops.

File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.8/subprocess.py", line 512, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command 'ping' returned non-zero exit status 127.

My question is how do I handle non-zero exit status using subprocess.check_output()

client.py snippet:

chan = client.get_transport().open_session()
    chan.send('Command Shell Open')
    while True:
        command = chan.recv(1024).decode()
        try:
          CMD = subprocess.check_output(command, shell=True)
            # CMD = subprocess.check_output(command, shell=True)
          chan.send(CMD)
        except subprocess.CalledProcessError as e:
            chan.send(e)
        client.close

server.py snippet:

try:
    t = paramiko.Transport(client)
    t.load_server_moduli()
    t.add_server_key(host_key)
    server = Server()
    t.start_server(server=server)

    chan = t.accept(20)
    print(chan.recv(1024))
    while True:
        command= raw_input("SHELL >> ").strip('n')
        chan.send(command)
        print(chan.recv(1024) + 'n')
🌐
Python.org
discuss.python.org › python help
Script works under Python 3.5.2, but not under 3.12.3 - Python Help - Discussions on Python.org
March 6, 2025 - I’m using a [script] program that works under Python 3.5.2, but not under 3.12.3. From my research, subprocess.check_output() was changed in the 3.12.3 library, and the syntax differs from earlier versions. I program i…
🌐
Linux find Examples
queirozf.com › entries › python-3-subprocess-examples
Python 3 Subprocess Examples
November 26, 2022 - import subprocess # errors in the created process are raised here too output = subprocess.check_output(["ls","-lha"],universal_newlines=True) output # total 20K # drwxrwxr-x 3 felipe felipe 4,0K Nov 4 15:28 . # drwxrwxr-x 39 felipe felipe 4,0K Nov 3 18:31 .. # drwxrwxr-x 2 felipe felipe 4,0K Nov 3 19:32 .ipynb_checkpoints # -rw-rw-r-- 1 felipe felipe 5,5K Nov 4 15:28 main.ipynb · Python version 3.5+ import subprocess # run() returns a CompletedProcess object if it was successful # errors in the created process are raised here too process = subprocess.run(['ls','-lha'], check=True, stdout=subprocess.PIPE, universal_newlines=True) output = process.stdout output # total 20K # drwxrwxr-x 3 felipe felipe 4,0K Nov 4 15:28 .
🌐
Scaler
scaler.com › home › topics › subprocess module in python
Subprocess Module in Python| Scaler Topics
November 3, 2022 - stdout: It represents the result ... Return Value: The Python subprocess.check_output() function generally returns the same output as the subprocess call()....