How Do You Write a Python Program That Can Run Linux Bash Commands?

Problem scenario
You want to use Python to run Linux commands.  You have been told to not use the "import os" for this task.  You want to manipulate the text and output of Bash commands for sophisticated processing and automation with Python.  How can a Python program run Bash commands?

Solution
Use "from subprocess import check_output" as the first line.  Then encapsulate the Bash command inside double quotes, square brackets and parentheses like these two lines of Python code:

out = check_output(["date"])
sn = check_output(["hostname"])

Later in your Python program, you will be able to use "out" and "sn" as the date and servername respectively.  Here is an example (test.py) of how to use the "date" and "hostname" Bash commands inside a Python script:

from subprocess import check_output
out = check_output(["date"])
sn = check_output(["hostname"])
for i in sn:
   print(i)
print(sn)
print(out)

If you are not constructing the Bash commands from an untrusted source, or you have a sanitation system for such input, you can use "shell=True".  This will enable you to invoke a wider range of Bash commands (including those with pipes "|") with greater complexity. Here is a Python 2 example of how to use "shell=True":

from subprocess import check_output
out = check_output(["cat /etc/*-release | grep NAME | grep PRETTY"], shell=True)
sn = check_output(["hostname"])
print out

The above in Python 3 is here:

from subprocess import check_output
out = check_output(["cat /etc/*-release | grep NAME | grep PRETTY"], shell=True).strip()
out = str(out)
out = out[1::]
sn = check_output(["hostname"])
print(out)

Leave a comment

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