Home » Python: execute shell commands (and get the output) with the os package

Python: execute shell commands (and get the output) with the os package

  • by
  • 2 min read
Tags:

Running shell (e.g. Bash) commands in Python is fairly easy using the os package. In this article, I outline two ways to run shell commands in Python: using the system method and the popen method.

This article is part of a two-part series related to running shell commands from within Python.

Execute shell commands using the os package

The most straightforward solution to running shell commands via Python is simply by using the system method of the os package. The os package “provides a portable way of using operating system dependent functionality.” The system method executes a string as a command in a subshell, which basically is an independent instance of the command processor of your operating system. For Windows, commands will be run using cmd.exe, for Linux this will be Bash, Mac will use Bash or Z shell.

The following code will open a subshell, run the command, and return the process exit code — a 0 (zero) if the command has run successfully, other numbers mean something has gone wrong (see Linux and Windows).

import os
os.system('echo "Hello World!"')

Execute shell commands and get the output using the os package

Sometimes, you’re not only interested in running shell commands, but you’d also like to know what printed output is. The os package also has a solution for this: the popen method. This method opens a pipe into the command, which is used to transfer its output to a Python variable.

The following code will once again open a subshell and run the command, but instead of returning the process exit code, it will return the command output. If you ‘d like to remove the trailing nextline (\n), you can use the strip method

output_stream = os.popen('echo "Hello World!"')
output_stream.read()

❗ Note the following:

  • If the command passed to the shell generates errors, it will only return two single quotes.
  • If you would like to know if a command completed successfully, you can access the process exit code using the close method. Like this:
output_stream = os.popen('non-existing-command')
output_stream.close()

The popen method of the os package uses the subprocess module. So instead of using popen, you might as well interface with the subprocess module directly. We discuss this in the next article.

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Leave a Reply

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