Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leave arguments untouched with argparse

I would like use argparse to parse the arguments that it knows and then leave the rest untouched. For example I want to be able to run

performance -o output other_script.py -a opt1 -b opt2

Which uses the -o option and leaves the rest untouched.

The module profiler.py does a similar thing with optparse, but since I'm using argparse I'm doing:

def parse_arguments():
    parser = new_argument_parser('show the performance of the given run script')
    parser.add_argument('-o', '--output', default='profiled.prof')

    return parser.parse_known_args()

def main():
    progname = sys.argv[1]
    ns, other_args = parse_arguments()
    sys.argv[:] = other_args

Which also seems to work, but what happens if also other_script.py also has a -o flag?

Is there in general a better way to solve this problem?

like image 387
andrea_crotti Avatar asked Jan 31 '12 17:01

andrea_crotti


2 Answers

You could also add a positional argument to your parser with nargs=argparse.REMAINDER, to capture the script and its options:

# In script 'performance'...
p = argparse.ArgumentParser()
p.add_argument("-o")
p.add_argument("command", nargs=argparse.REMAINDER)
args = p.parse_args()
print args

Running the above minimal script...

$ performance -o output other_script.py -a opt1 -b opt2
Namespace(command=['performance', '-a', 'opt1', '-b', 'opt2'], o='output')
like image 109
chepner Avatar answered Nov 12 '22 13:11

chepner


argparse will stop to parse argument until EOF or --. If you want to have argument without beeing parsed by argparse, you can write::

python [PYTHONOPTS] yourfile.py [YOURFILEOPT] -- [ANYTHINGELSE]
like image 21
tito Avatar answered Nov 12 '22 14:11

tito