Search code examples
pythonpython-2.7python-module

Python calling a module that uses argparser


This is probably a silly question, but I have a python script that current takes in a bunch of arguments using argparser and I would like to load this script as a module in another python script, which is fine. But I am not sure how to call the module as no function is defined; can I still call it the same way I do if I was just invoking it from cmd?

Here is the child script:

import argparse as ap
from subprocess import Popen, PIPE

parser = ap.ArgumentParser(
    description='Gathers parameters.')
parser.add_argument('-f', metavar='--file', type=ap.FileType('r'), action='store', dest='file',
                    required=True, help='Path to json parameter file')
parser.add_argument('-t', metavar='--type', type=str, action='store', dest='type',
                    required=True, help='Type of parameter file.')
parser.add_argument('-g', metavar='--group', type=str, action='store', dest='group',
                    required=False, help='Group to apply parameters to')
# Gather the provided arguments as an array.
args = parser.parse_args()

... Do stuff in the script

and here is the parent script that I want to invoke the child script from; it also uses arg parser and does some other logic

from configuration import parameterscript as paramscript

# Can I do something like this?
paramscript('parameters/test.params.json', test)

Inside the configuration directory, I also created an init.py file that is empty.


Solution

  • The first argument to parse_args is a list of arguments. By default it's None which means use sys.argv. So you can arrange your script like this:

    import argparse as ap
    
    def main(raw_args=None):
        parser = ap.ArgumentParser(
            description='Gathers parameters.')
        parser.add_argument('-f', metavar='--file', type=ap.FileType('r'), action='store', dest='file',
                            required=True, help='Path to json parameter file')
        parser.add_argument('-t', metavar='--type', type=str, action='store', dest='type',
                            required=True, help='Type of parameter file.')
        parser.add_argument('-g', metavar='--group', type=str, action='store', dest='group',
                            required=False, help='Group to apply parameters to')
        # Gather the provided arguments as an array.
        args = parser.parse_args(raw_args)
        print(vars(args))
    
    
    # Run with command line arguments precisely when called directly
    # (rather than when imported)
    if __name__ == '__main__':
        main()
    

    And then elsewhere:

    from first_module import main
    
    main(['-f', '/etc/hosts', '-t', 'json'])
    

    Output:

    {'group': None, 'file': <_io.TextIOWrapper name='/etc/hosts' mode='r' encoding='UTF-8'>, 'type': 'json'}