How Do You Fix a Python Program That Returns an Error “…subprocess.py … in check_output”?

Problem scenario
You are trying to use subprocess and check_output in Python to run raw Bash/shell/Linux commands.  

Your Python program has a line like this:
subprocess.check_output("/usr/local/bin/coolprog arg1 /path/to/file.txt arg3")

You get this error when you run the program:

 File "/usr/lib/python2.7/subprocess.py", line 566, in check_output

What do you do?

Solution
This solution only applies if the Bash command is constructed from known good input.  If the command that the subprocess invocation is constructed from is an external source, this solution would inadvisable; we do not recommend you adapt this solution to something that could be susceptible to malicious code injections.

The above subprocess.checkoutput line works for a single-word Linux command.  For commands with more involved syntax, you must change it to include "shell=True" after a comma and space; you also need a .split() at the end of the closing parenthesis above.  Here is an example of how to properly use check_output:

subprocess.check_output("/usr/local/bin/coolprog arg1 /path/to/file.txt arg3", shell=True).split()

# If you want to learn more about the safety concerns of subprocess and shell=True, see this link.

Leave a comment

Your email address will not be published.