Search code examples
pythoncmdprogram-entry-pointargparse

Passing directory paths as strings to argparse in Python


Scenario: I have a python script that receives as inputs 2 directory paths (input and output folders) and a variable ID. With these, it performs a data gathering procedure from xlsx and xlsm macros, modifies the data and saves to a csv (from the input folder, the inner functions of the code will run loops, to get multiple files and process them, one at a time).

Issue: Since the code was working fine when I was running it from the Spyder console, I decided to step it up and learn about cmd caller, argparse and the main function. I trying to implement that, but I get the following error:

Unrecognized arguments (the output path I pass from cmd)

Question: Any ideas on what I am doing wrong?

Obs: If the full script is required, I can post it here, but since it works when run from Spyder, I believe the error is in my argparse function.

Code (argparse function and __main__):

# This is a function to parse arguments:
def parserfunc():
    import argparse
    parser = argparse.ArgumentParser(description='Process Files')
    parser.add_argument('strings', nargs=3)
    args = parser.parse_args()
    arguments = args.strings
    return arguments

# This is the main caller    
def main():
    arguments = parserfunc()
    # this next function is where I do the processing for the files, based on the paths and id provided):
    modifierfunc(arguments[0], arguments[1], arguments[2])

#
if __name__ == "__main__":
    main()

Solution

  • If you decided to use argparse, then make use of named arguments, not indexed. Following is an example code:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('input')
    parser.add_argument('output')
    parser.add_argument('id')
    
    args = parser.parse_args()
    print(args.input, args.output, args.id) # this is how you use them
    

    In case you miss one of them on program launch, you will get human readable error message like

    error: the following arguments are required: id