0% found this document useful (0 votes)
239 views1 page

Python3 Subprocess Guide

The document provides an overview of using the subprocess module in Python. It discusses different ways to execute commands and get output, handle processes, and use subprocess for threading. It includes examples of calling external programs, getting process IDs, communicating with processes, and using subprocess in scripts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
239 views1 page

Python3 Subprocess Guide

The document provides an overview of using the subprocess module in Python. It discusses different ways to execute commands and get output, handle processes, and use subprocess for threading. It includes examples of calling external programs, getting process IDs, communicating with processes, and using subprocess in scripts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python3 – Subprocess Overview

One-liner (Same Task) Migrate os to subprocess


• print(subprocess.check_output(['ls', '-1']).decode('utf-8')) • os: output = [Link](os.P_WAIT, 'cmd', “arg')
• print(''.join(map(chr, subprocess.check_output(['ls', '-1'])))) • subprocess: output = call(['cmd', 'arg'])

Waits (No Threading) • os: pid = [Link](os.P_NOWAIT, 'cmd', 'arg')


[Link](), subprocess.check_output(), • subprocess: pid = Popen(['cmd', 'arg']).pid
[Link](),
[Link]().[Link]() Environment Variables
Threading proc = [Link](['echo',
[Link]() [Link]['MY_ENV_VAR']])
#Windows only (threading)
DETACHED_PROCESS = 0x00000008 proc = [Link]('echo '$MY_ENV_VAR'',
[Link]([[Link], 'ls'], env=environ, shell=True)
creationflags=DETACHED_PROCESS).pid
#BSD only (threading) proc = [Link](['echo',
pid = [Link]([[Link], 'ls'], [Link]('$MY_ENV_VAR')])
stdout=[Link], stderr=[Link],
stdin=[Link]) • newenv = [Link]()
• newenv['MY_ENV_VAR'] = 'value'
Open Program or Execute Code
[Link](['EXCUTABLE']) # no threading Example
import subprocess
Get PID proc = [Link]('mousepad')
pid = [Link](['ls', '-1'], shell=True, print(proc) # <[Link] object at
stdout=[Link], 0x7f3240609d30>
stderr=[Link]).[Link]() pid = [Link] # 13731
print([Link]()) # None
print(pid) # <[Link] object at 0x7f32405e80b8> [Link]()
print([Link]()) # 0
type(pid) # [Link] proc = [Link]('mousepad')
pid = [Link]
# .readline() reads one stdout line at a time try:
# .readlines() reads all stdout at once outs, errs = [Link](timeout=15)
except TimeoutExpired: # when timer expires
Usage [Link]() # close mousepad
x = subprocess.check_output(['cmd', 'arg1']) outs, errs = [Link]()
# x = b'Desktop\nDocuments\nDownloads\n'
z = [Link]('utf-8')) # plain text (str) # Example Lines
• [Link](input='', timeout=int)
[Link]('ls -l') # one str param • Return Code: p_status = [Link]()
# Output = 'String\nString\nString'
• Send a Kill Signal: proc.send_signal(SIG)
Tricks • Stop the Process: [Link]()
[Link]('ls -l') # output: ['ls', '-l'] • Wait for the Process: [Link]()
subprocess.check_output([Link]('ls -l'))
Scripted Example
Shell2Python #!/usr/bin/env python3
Shell: output=`dmesg | grep hda` import subprocess, sys
Python: from subprocess import * cmd = 'netstat -p --tcp'
p1 = Popen(['dmesg'], stdout=PIPE) p = [Link](cmd, shell=True,
p2 = Popen(['grep', 'hda'], stdin=[Link], stdout=PIPE) stderr=[Link])
[Link]() while True: # displaying output immediately
# allow p1 to receive a SIGPIPE if p2 exits out = [Link](1)
output = [Link]()[0] if out == '' and [Link]() != None:
Python: break # exit after netstat closes
output = check_output('dmesg | grep hda', shell=True) if out != '': # release output
[Link](out)
[Link]()

Created by Devyn Collier Johnson <DevynCJohnson@[Link]> (2015 v2) More cheatsheets at [Link]

You might also like