Using subprocess Module

From PeformIQ Upgrade
Jump to navigation Jump to search

Source

Some examples of using the the subprocess module.

From - http://stackoverflow.com/questions/984941/python-subprocess-popen-from-a-thread

#!/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