Python Forum
python create function validation - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: python create function validation (/thread-38708.html)



python create function validation - mg24 - Nov-15-2022

Hi Team,

how to create separate function for validating command line arguments in another module
and import the same in main module


def main():
    print("Directory watcher application")

    if (len(argv) < 2):
        print("Insufficient arguments")
        exit()

    if (argv[1] == "-h"):
        print("This script will travel the directory and display the names of all entries")
        exit()

    if (argv[1] == "-u"):
        print("Usage : Application_name Direcory_Name")
        exit()

    Directory_Watcher(argv[1])


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



RE: python create function validation - deanhystad - Nov-15-2022

Command line parsing and verification is hard. Maybe not in this case, but quite often it can be hard. Use argparse if the command line is fairly simple. Use Click for a complicated command line interface. Both provide verification and even help (or --help).

A stab at using argparse to parse the 1 positional argument.
import argparse

def directory_watcher(directory):
    print("Watching", directory)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        prog="dir_watcher",
        description="Travel the directory and display names of all entries")
    parser.add_argument("directory", help="Directory to watch")
    args = parser.parse_args()
    directory_watcher(arg.directory)
argparse automatically creates -h --help
If you really want usage, that could be an optional argument. How is -u different from -h?
Output:
> python dir_watcher.py -h usage: dir_watcher [-h] directory Travel the directory and display names of all entries positional arguments: directory Directory to watch optional arguments: -h, --help show this help message and exit > > > python dir_watcher.py stuff Watching stuff