Search code examples
pythonvalidationargv

Python argv validation


I need to check if the user is giving the input file and the name of the output, and I'm doing the following:

def main():
    if len(argv) > 2:
        script, file_in, file_out = argv
        execute_code(file_in, file_out)
    else:
        print "Wrong number of arguments!"
        print "Usage: python script.py filename_input filename_output"


if __name__ == '__main__':
    main()

Is there other way to check if the argv arguments are correct?


Solution

  • You'd use argparse:

    The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv.

    For example your main function could be rewritten as

    import argparse
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument('file_in', help='input file')
        parser.add_argument('file_out', help='output file')
        args = parser.parse_args()
        execute_code(args.file_in, args.file_out)
    
    if __name__ == '__main__':
        main()
    

    argparse will perform validation for you and display fairly helpful error messages if some of the required arguments are missing:

    vaultah@base:~$ python3 /home/vaultah/untitled.py
    usage: untitled.py [-h] file_in file_out
    untitled.py: error: the following arguments are required: file_in, file_out
    vaultah@base:~$ python3 /home/vaultah/untitled.py in
    usage: untitled.py [-h] file_in file_out
    untitled.py: error: the following arguments are required: file_out
    

    Additionally, it will generate a help message

    vaultah@base:~$ python3 /home/vaultah/untitled.py -h
    usage: untitled.py [-h] file_in file_out
    
    positional arguments:
      file_in     input file
      file_out    output file
    
    optional arguments:
      -h, --help  show this help message and exit