Python subprocess: Difference between revisions
Line 41: | Line 41: | ||
import subprocess | import subprocess | ||
# | # don't open new console window for subprocess | ||
startupinfo = subprocess.STARTUPINFO() | startupinfo = subprocess.STARTUPINFO() | ||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW | startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW |
Revision as of 15:55, 18 September 2021
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.
TODO:
document windows specific issues
SubProcesses
Basics
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=pip.stdout, stdout=subprocess.PIPE) (stdout, stderr) = pipe2.communicate()Windows
Windows executables are either built as console-applications (require console) or gui-applications (do not show console).
On windows, you can usepythonw.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'