Search code examples
pythonpython-2.7functionargparse

How do I return a value to main from a function called by an argparse function


Novice Python student here (running 2.7) trying to out my understanding of functions and argparse...sometimes together.

I have a main function that calls an argparse function, which has an argparse command line argument (-i/--input) that calls a path_check function, which validates the path passed in the input argument. Now I do not how to return the validated input path back to my main function since the path_check function is not called in main. Also wondering if there's a better way to structure this (not sure if a class is appropriate here).

#!/bin/user/python

import os,sys
import argparse  

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input",help="source directory",
        required=True,type=path_check)
    args = parser.parse_args()

def path_check(arg):
    if not os.path.exists(arg):
        print("Directory does not exist. Please provide a valid path")
    else:
        return arg

def main():
    '''
    This main script analyzes the source folder and redirects
    files to the appropriate parsing module
    '''
    parse_args()
    source = path_check() # This is the problem area

if __name__ == "__main__": main()

The error received is

TypeError: path_check() takes exactly 1 argument (0 given)

EDIT: Here is the corrected code if it's helpful for anyone. I needed to add a description to the argparse argument so I had a means of calling the argument's value, which I could then return.

 #!/bin/user/python

import os,sys
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input",help="source directory",
        dest="input",required=True,type=path_check)

    args = parser.parse_args()
    return args.input

def path_check(arg):
    if not os.path.exists(arg):
        print("Directory does not exist. Please provide a valid path")
    else:
        return arg

def main():
    '''
    This main script analyzes the source folder and redirects
    files to the appropriate parsing module
    '''
    source = parse_args()

if __name__ == "__main__": main()

Solution

  • def parse_args():
        parser = argparse.ArgumentParser()
        parser.add_argument("-i", "--input",help="source directory",
            required=True,type=path_check)
        args = parser.parse_args()
        return args     # <====
    
    def main():
        '''
        This main script analyzes the source folder and redirects
        files to the appropriate parsing module
        '''
        args = parse_args()      # <===
        source = path_check(args.input) # <===
    

    parse_args function has to return the args variable to main. And then main has to pass its input attribute to path_check.

    args.input will be the string that you provided in the command line.

    args is a simple argparse.Namespace object with attributes that correspond to each of arguments that you defined in the parser. Some of those attributes may have a value of None, depending on how the defaults are handled.

    During debugging it is a good idea to include a

    print(args)
    

    statements, so you see what you get back from the parser.