Python subprocess

From wikinotes

If you want to run a command on the host operating system, you'll want to use python's subprocess module. It provides a means of safely spawning a subprocess, and passing parameters in a way that does not expose security vulnerabilities.

There are a lot of variations on how this can be used, these are only the methods I use most frequently.



Popen Shortcuts

import subprocess

# shortcuts
subprocess.check_call(['netstat', '-an'], universal_newlines=True)

The Popen objects are the most powerful, but most verbose way of managing processes.

# redirecting streams between processes
pipe1 = subprocess.Popen(['tasklist'], stdout=subprocess.PIPE)
pipe2 = subprocess.Popen(['find', '/I', 'python'], stdin=pipe1.stdout, stdout=subprocess.PIPE)
(stdout, stderr) = pipe2.communicate()


Windows executables are either built as console-applications (require console) or gui-applications (do not show console).
On windows, you can use pythonw.exe to launch an application without a console.
Regardless of this decision, you can control whether or not a subprocess should open a new console while it runs.

import subprocess

# don't open new console window for subprocess
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(['foo.exe'], startupinfo=startupinfo)

Process Exitcodes

import sys

sys.exit(1)  # exit with fail

Environment Variables

import os

os.environ['FOO'] = 'bar'