Using Python How Do You Run Bash Commands That Include More Than One Word?

Problem scenario
You are trying to have Python run Bash commands. As soon as the command includes a flag or a second argument, there is no value being assigned in Python. Two or more words in the Bash command cause no value to be assigned. What can you do?

Solution
This only works if you have complete control of the Bash command arguments. This should not be done with uncleansed data (e.g., user input). Use the shell=True argument (if you know it will be acceptable from a security perspective):

import subprocess
…
proc = subprocess.Popen(['ls', '-lh'], shell=True, stdout=subprocess.PIPE)

# Some people caution against the stdout=subprocess.PIPE.  The biggest potential security flaw is the shell=True however.  Use with care.

Leave a comment

Your email address will not be published. Required fields are marked *