Monday, May 2, 2016

runcmd and runcmds: probably the based usage of single and multi commands run

#!/usr/bin/env python
import shlex
import subprocess
import os

# command run
def runcmd(cmd):
    cmd =  shlex.split(cmd)
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, error = proc.communicate()
        return out + error
    except:
        print 'Invalid Command: ' + str(cmd)
        return -1

# multiple commands in a process
def runcmds(cmds_list):
    bash_path = runcmd('which bash').strip() # strip() used to trim line feed
    p = os.popen('%s' % bash_path, 'w')
    for cmd in cmds_list:
        p.write('%s\n' % cmd)
    status = p.close()

    if status is None:
        print 'Commands executed OK'
    else:
        print 'One or more command failed to run'

    return status

if __name__ == '__main__':
    l = ['mongo', 'show dbs']   
    print runcmds(l)

No comments:

Post a Comment