Call a system command from Python

Python commands - The easy way


A quick and dirty way to send commands to the shell is with the OS module. But you have little control of what happens once you call the command, and no real way to interact with the subprocess that gets spawned.

import os
os.system('ls -l')

The Correct Way - Subprocess Module

Subprocess Module - Simple command

Below is the code from the video, I have added in text=True so you don't need to use the '.decode('utf-8') method.

import subprocess
results =["ls", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

Subprocess Module - Output to a file

Here's the example from the video where I redirect the output to a file.

with open('out.txt', 'w') as f:
    results =["ls", "-l"], stdout=f, stderr=subprocess.PIPE)

Subprocess Module - Long processes in the background using Popen

If you need to control the state of the process, you need to use Popen. Here is the code I used in the video.

import subprocess
process = subprocess.Popen(['ping', '-n', '10', ''],
stdout, stderr = results.communicate()
stdout, stderr