2

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)
fugu
  • 6,417
  • 5
  • 40
  • 75
  • 1
    Why don't you use `argparse`? `optparse` is long deprecated – Chris_Rands Feb 12 '18 at 15:54
  • 1
    You're actually never using the args as you have recalled the get_args func. and overwrite the args variable – harshil9968 Feb 12 '18 at 15:54
  • @Chris_Rands - how would that help? – fugu Feb 12 '18 at 16:21
  • I've the same problem, even though the main() function of the script I got does not have any input arguments. So when I call the script from the command line with optional arguments it works just fine, but when I import the script and then call the main() function with the optional parameters in a list, it doesn't work because the main function has no input argument. – Svenno Nito Jan 19 '20 at 00:20

0 Answers0