I have a module myModule.py
that takes an input file and a number, parses the arguments using OptionParser and prints them:
python myModule.py -i "this_file" -n 100
('this_file', '100')
I am trying to call this from another script, so that I can work with the returned values. After following advice in this question I'm importing main()
from my module and making a dictionary of args:values
which I then provide as input to the imported main()
function:
However this is not working and dies with the error:
Traceback (most recent call last):
File "call_module.py", line 8, in <module>
fileIn, number_in = main(**args)
TypeError: main() got an unexpected keyword argument 'in_file'
I've also tried passing a the args as a list:
args = ['-i','this_file', '-n', 100]
fileIn, number_in = main(args)
This prints:
(None, None)
(None, None)
Can anyone suggest what I'm doing wrong here?
Here is my module containing main()
:
myModule.py
#!/usr/bin/env python
import os, re, sys
from optparse import OptionParser
def get_args():
parser = OptionParser()
parser.add_option("-i", \
"--in_file", \
dest="in_file",
action="store")
parser.add_option("-n", \
"--number", \
dest="number",
action="store")
options, args = parser.parse_args()
return(parser)
def main(args):
parser = get_args()
options, args = parser.parse_args()
fileIn = options.in_file
number_in = options.number
print(fileIn, number_in)
return(fileIn, number_in)
if __name__ == "__main__":
# sys.exit(main())
parser = get_args()
args = parser.parse_args()
main(args)
And the script I'm using to call main()
:
call_module.py
import os, re, sys
from myModule import main, get_args
# args = { "in_file": 'this_file',
# "number" : 100 }
args = ['-i','this_file', '-n', 100]
print(args)
fileIn, number_in = main(args)
print(fileIn, number_in)