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!