0

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 ...

Community
  • 1
  • 1
Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36

2 Answers2

1

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:])
Community
  • 1
  • 1
Ajeet Ganga
  • 8,353
  • 10
  • 56
  • 79
1

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:])
David Z
  • 128,184
  • 27
  • 255
  • 279
  • Thanks exactly what I needed, do you have some documentation about sys, as I may want to manipulate the arguments a bit. – Othman Benchekroun Dec 20 '16 at 10:00
  • Oh, it's my first time using python, I just realised sys is the basic way to read arguments. Thank you. I tried the code with `python myScript.py cd -`, but It returned an error. Do you know why maybe ? – Othman Benchekroun Dec 20 '16 at 10:05