Process Command Line Arguments in Python

To access command line arguments in python one can use sys.argv.

sys.argv is a list containing the parameters with which the script was called, including the name of the script at index 0 of the list - sys.argv[0], so in sys.argv[1:] we find the arguments with which the script was called.

To parse the list of arguments, getopt.getopt is used.

Syntax: getopt.getopt(args, options, [long_options])

(Options that require an argument should be followed by a colon (:).)

See the example below:


try:
        (options, args) = getopt.getopt(sys.argv[1:], 'n:hv')
    except getopt.GetoptError:
        usage()

    if len(args) != 1:
        usage()

    for (opt, optval) in options:
        if opt == "-n":
            name = optval
        elif opt == "-h":
            show_help = 1
        elif opt == "-v":
            verbose = True



Comentarii

Postări populare de pe acest blog

SQL injection with UNION

Docker compose DNS resolution