Using subprocess Module
Revision as of 09:36, 15 September 2015 by PeterHarding (talk | contribs)
Source
Some examples of using the the subprocess module.
#!/usr/bin/env python import subprocess def execute(command): tokens = command.split() print tokens process = subprocess.Popen(tokens, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = '' # Poll process for new output until finished for line in iter(process.stdout.readline, ""): print line, output += line process.wait() exitCode = process.returncode if (exitCode == 0): return output else: raise Exception(command, exitCode, output) execute('ping -c 23 127.0.0.1')
Using threads
!/usr/bin/env python import threading import subprocess #--------------------------------------------------------------------------- class Threader(threading.Thread): #------------------------------------------------------------------- def __init__(self): self.stdout = None self.stderr = None threading.Thread.__init__(self) #------------------------------------------------------------------- def run(self): p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.stdout, self.stderr = p.communicate() #------------------------------------------------------------------- #--------------------------------------------------------------------------- threader = Threader() threader.start() threader.join() print threader.stdout
Same logic not using threads.
#!/usr/bin/env python import threading import subprocess #--------------------------------------------------------------------------- p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() #--------------------------------------------------------------------------- print stdout
OpenSSL CSR example
#!/usr/bin/env python import threading import subprocess #--------------------------------------------------------------------------- p = subprocess.Popen('openssl req -in /tmp/csr.txt -noout -text'.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() #--------------------------------------------------------------------------- print stdout