Running External Programs in Python

Naveera A.

The Problem

How can you execute an external program or call a system command from within a Python program?

Let’s say you are working on an inherited shell script. Reimplementing the script in Python would take a long time. How can you run those shell commands from within Python?

The Solution

The recommended method for subprocess management in Python is to use Python’s subprocess module.

The subprocess module replaced many older modules and functions like the os.system module.

The easiest way to use the subprocess module is to use the run() function. The run() function can handle most of the use cases and the official documentation recommends using it for all use cases it can handle. For more advanced use cases, we can use the underlying Popen class.

We can use the run() function to execute shell commands in a UNIX environment, like so:

>>> import subprocess >>>['ls']) CompletedProcess(args=['ls'], returncode=0)

On completion of a process, the run() function will return an instance of the CompletedProcess class.

The important thing to keep in mind is that the run() function bypasses the shell and makes a system call directly. Any command that is a part of the shell itself, and not a separate executable, may not work this way.

For example, running the above code on Windows will result in an error:

>>> import subprocess >>>['ls']) Traceback (most recent call last): ... FileNotFoundError: [WinError 2] The system cannot find the file specified

We get the above error because in Windows ls is a part of PowerShell itself and not a standalone executable that can be called directly.

To run a shell command using the run() function, we need to provide some extra arguments. We need to pass the name of the shell, the -Command flag to indicate that we want it to run a specific command, and then finally the command itself, like so:['pwsh', '-Command', 'ls'])

Interacting with the text-based programs that are available on the shell is one of the most popular use cases of the subprocess module. But using the subprocess module, we can access any application on our computer, not just the text-based ones.

For example, we can write the following code to open Notepad:

import subprocess["notepad"])

In the case of opening Notepad, the process is marked complete when we close the Notepad window.

We can even run a Python script from within our parent Python script, like so:

import subprocess["python", ""])

However, bear in mind that using subprocess to write concurrent code is not recommended.

Get Started With Sentry

Get actionable, code-level insights to resolve Python performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a Python project and note your DSN

  3. Grab the Sentry Python SDK

pip install --upgrade sentry-sdk
  1. Configure your DSN
import sentry_sdk sentry_sdk.init( "https://<key><project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )

Check our documentation for the latest instructions.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.