The Python supports the programs that can be run on the command line, whole with command line arguments. It is the input parameter that wishes to be surpassed to the script when executing them.
It capability to interact with a command-line interface for the scripts.
It affords a getopt module, in which command line arguments and options can be parsed.
What is argument passing?
The command ls is frequently used to get a summary of files and folders current in a particular directory.
Why to use argparse?
It skill to talk between the author of a program and consumer which does not require going into the code and making changes to the script. It provides the capacity to a person to enter into the command-line arguments.
Access command line arguments
The Python sys module affords get right of entry to to command-line arguments by sys.argv. It solves the two purposes:
Python sys module
It is a basic module that was shipped with Python distribution from the early days on. It is a similar method as C library the use of argc/argv to get entry to the arguments. The sys module implements command-line arguments in a simple listing structure named sys.argv.
Each list aspect represents a single argument. The first one — sys.argv — is the name of Python script. The other list elements are sys.argv to sys.argv[n]- are the command line arguments two to n. As a delimiter between arguments, house is used. Argument values that incorporate area in it have to be quoted, accordingly.
It shops command-line arguments into a list; we can access it using sys.argv. This is very beneficial and a easy way to study command-line arguments as String.
import sys print(type(sys.argv)) print('The command line arguments are:') for i in sys.argv: print(i)
Python getopt module
The Python getopt module extends the separation of the input string via parameter validation. Based on getopt C function, it approves both quick and lengthy options, such as a fee assignment.
It is very similar to C getopt() feature for parsing command line parameters.
It is useful in parsing command line arguments where we choose the user to enter some options.
import getopt import sys argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file=']) print(opts) print(args) except getopt.GetoptError: # Print a message or do something useful print('Something went wrong!') sys.exit(2)
Python argparse module
It gives a command-line interface with standardized output, whereas the former two options leave most of the work in your hands. argparse lets in verification of constant and non-obligatory arguments with a title checking as both UNIX or GNU style. It is the preferred way to parse command-line arguments. It provides a lot of option such as positional arguments, the default cost for arguments, helps message, specifying the records kind of argument etc.
It makes it handy to write the user-friendly command-line interfaces. It automatically generates help and usage messages and problems errors when a user offers invalid arguments to the program.
This approach is used for parsing the command line selections and parameter list.
getopt.getopt(args, options, [long_options])
args- It is an argument listing that needs to be parsed.
options- A string of choice letters that the script desires to recognize, with alternatives that require an argument which need to be accompanied by way of a colon(:).
long_options(optional)- It need to be a string with names of the long options, which have to be supported.
This method returns a value consisting of two elements, i.e. list of (option, value) pairs, list of program arguments left after option list was stripped.
Each option-and-value pair are returned as an option as its first element, prefixed with a hyphen for short options (e.g.,’-x’) or two hyphens for long options (e.g., ‘–long-option’).
This exception arises when an unrecognized option is discovered in the argument list or when any alternative requiring an argument is given none.
The argument to the exception is a string that suggests the reason of the error. The attributes msg and decide to supply the error message and related option.
#!/usr/bin/python import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile> -o <outputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg print 'Input file is "', inputfile print 'Output file is "', outputfile if __name__ == "__main__": main(sys.argv[1:])
$ test.py -h usage: test.py -i <inputfile> -o <outputfile> $ test.py -i BMP -o usage: test.py -i <inputfile> -o <outputfile> $ test.py -i inputfile Input file is " inputfile Output file is "
How to use command line arguments in python?
Module Use Python version sys All arguments in sys.argv (basic) All argparse Build a command line interface >= 2.3 docopt Created command line interfaces >= 2.5 fire Automatically generate command line interfaces (CLIs) All optparse Deprecated < 2.7 Docopt Docopt is used to create command line interfaces. from docopt import docopt if __name__ == ‘__main__’: arguments = docopt(__doc__, version=’Example 1′) print(arguments) Fire Python Fire robotically generates a command line interface; you solely want one line of code. Unlike the different modules, it works instantly. You don’t want to outline any arguments; all the strategies are linked with the aid of default. To set up it type: pip deploy fireplace Define or use a class: import fire class Python(object): def hello(self): print(“Hello”) def openfile(self, filename): print(“Open file ‘” + filename + “‘”) if __name__ == ‘__main__’: fire.Fire(Python) You have the selections matching to the classification methods: python example.py good day python example.py openfile filename.txt Next TopicPython Tutorial ← Prev Next →