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

Question:

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()
Asked By: the_word

||

Answers:

To clarify the above stated comment, you need to include argument here

source = path_check(argument)
Answered By: Hisagr

When calling a function in main, if you want to pass some variable you need to insert them in the brackets.

function(Variable1, Variable2,)

and dont forget to put them on the function itself to accept the variable. To return a variable to your main function, simply at the end of the function do a return VariableName as well as adding it in front of the call in main followed by a = sign.

example:

main()
   x = 1
   ReturnVariable = function1(x)

function1(x)
   ReturnVariable = x * 2
   return ReturnVariable
Answered By: MrDucky38
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.

Answered By: hpaulj

I usually write the codes separately to keep things easier. I provide my code below for reference.

#!/bin/user/python
import os, sys
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input")    
    args = parser.parse_args()
    return 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
    '''
    args = parse_args()
    if not os.path.exists(args.input):
        print("Directory does not exist. Please provide a valid path")
    else:
        source = args.input

if __name__ == "__main__": 
    main()
Answered By: Chen Lin