Forward a shell command using python

443 views Asked by At

So to be more precise, what I am trying to do is :

  • read a full shell command as argument of my python script like : python myPythonScript.py ls -Fl
  • Call that command within my python script when I'd like to (Make some loops on some folders and apply the command etc ...)

I tried this :

import subprocess
from optparse import OptionParser
from subprocess import call
def execCommand(cmd):
        call(cmd)


if __name__ == '__main__':
        parser = OptionParser()
        (options,args) = parser.parse_args()
        print args
        execCommand(args)

The result is that now I can do python myPythonScript.py ls , but I don't know how to add options. I know I can use parser.add_option , but don't know how to make it work for all options as I don't want to make only specific options available, but all possible options depending on the command I am running. Can I use something like parser.add_option('-*') ? How can I parse the options then and call the command with its options ?

EDIT

I need my program to parse all type of commands passed as argument : python myScript.py ls -Fl , python myScript.py git pull, python myScript rm -rf * etc ...

2

There are 2 answers

2
David Z On BEST ANSWER

OptionParser is useful when your own program wants to process the arguments: it helps you turn string arguments into booleans or integers or list items or whatever. In your case, you just want to pass the arguments on to the program you're invoking, so don't bother with OptionParser. Just pass the arguments as given in sys.argv.

subprocess.call(sys.argv[1:])
3
Ajeet Ganga On

Depending on how much your program depends on command line arguments, you can go with simple route.

Simple way of reading command line arguments

Use sys to obtain all the arguments to python command line.

import sys
print  sys.argv[1:]

Then you can use subprocess to execute it.

from subprocess import call
# e.g. call(["ls", "-l"])
call(sys.argv[1:])

This sample below works fine for me.

import sys 
from subprocess import call
print(sys.argv[1:])
call(sys.argv[1:])