Run shell command from Python script

Q: How can I execute a shell command from my Python script on a Raspberry Pi?

A: You can use the subprocess package; Subprocess allows you to create new processes and connect to their input/output pipes and catch errors.

Here’s a synopsis for the command:, *, stdin=None, stdout=None, stderr=None, shell=False)

Here’s a Python script that uses a shell command to list the contents of the current directory:

import subprocess
subprocess.check_call(["ls", "-l"])

The full manual for subprocess can be found here.