3

I have a script called mymodule.py that uses argparse. I want to be able to write a script fakemicro.py that will be able to import the main module from mymodule.py and pass arguments to it. My code is based around Brian's answer here: https://www.reddit.com/r/learnpython/comments/3do2wr/where_to_put_argparse/ and the accepted answer here: In Python, can I call the main() of an imported module?

I keep getting unexpected errors so I hoped that you could help.

Here's the content of mymodule.py:

#!/usr/bin/env python
import argparse
import sys
def parse_args(args):
    parser = argparse.ArgumentParser(
        description='yeah'
    )
    parser.add_argument(
        '-i', nargs='+',
        help='full path of input directory', required=True
    )
    parser.add_argument(
        '-o', '-output',
        help='full path of output directory', required=True
    )
    parsed_args = parser.parse_args()
    return parsed_args


def main(args):
    args = parse_args(args)
    print args.i
    print args.o
if __name__ == '__main__':
    main(sys.argv[1:])

and here is fakemicro.py:

#!/usr/bin/env python

import mymodule
import sys
mymodule.main(['-i', sys.argv[1], '-o', sys.argv[2]])

I was expecting that this would function as if I had typed: mymodule.py -i path/to/1 -o path/to/2 in the command line but instead my script broke.

$ fakemicro.py path/to/2 path/to/3
usage: fakemicro.py [-h] -i I [I ...] -o O
fakemicro.py: error: argument -i is required

I thought that mymodule.py would have seen that I passed -i arg1 -o arg2 via mymodule.main(['-i', sys.argv[1], '-o', sys.argv[2]]) ?

here is what the output of mymodule.py looks like when run by itself on the command line:

$ mymodule.py -i 1 -o 2
['1']
2

Any help would be really appreciated. Thanks!

Tandy Freeman
  • 528
  • 5
  • 15
  • `mymodule` doesn't run by itself, does it? You aren't using the `args` parameter. – hpaulj Jun 30 '17 at 15:49
  • so sorry,I didn't import sys either. I added args = parse_args(args) and now mymodule.py returns the expected value when run as is. i'll edit my original post to reflect this. – Tandy Freeman Jun 30 '17 at 15:59

1 Answers1

2

I figured it out. I didn't pass the args argument to parsed_args = parser.parse_args() . As such, the parser object was using sys.argv[1:] as its source, and not whatever was passed as args. Changing that line to parsed_args = parser.parse_args(args) solved the issue.

Tandy Freeman
  • 528
  • 5
  • 15