Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What library is used to write Python command line programs

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what library to write Python command line program". In daily operation, I believe that many people have doubts about what library to write Python command line program. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "what library to write Python command line program". Next, please follow the editor to study!

First, the design concept

Before we discuss the design concept of each library, let's design a calculator program. In fact, this example appeared in the first article of the argparse library, that is:

The command line program accepts a position parameter that can appear multiple times and is a number

By default, the command line program calculates the maximum value of a given string of numbers

If the option parameter, sum, is specified, the sum of the given string of numbers will be calculated.

It is hoped that their design concepts can be further understood from the code that each library implements the example.

2.1 、 argparse

The design philosophy of argparse is to provide you with the finest-grained control, and you need to tell it in detail whether the parameter is an option parameter or a position parameter, what the type of parameter value is, and how the parameter is handled. In short, it is like a first-generation robot without intelligent analysis ability. you need to tell it clear information before it will help you do things according to the given information.

The following example is a calculator program implemented by argparse:

Import argparse # 1. Set the parser parser = argparse.ArgumentParser (description='Calculator Program.') # 2. Define parameter # add location parameter nums, shown in help information as num # its type is int, and multiple inputs are supported, and at least one parser.add_argument ('nums', metavar='num', type=int, nargs='+', help='a num for the accumulator') # add option parameter-sum is required After the parameter is parsed by parser, the corresponding attribute name is accumulate # if-- sum is not provided, the default value is max function, otherwise it is sum function parser.add_argument ('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the nums (default: find the max)') # 3. Parsing parameter args = parser.parse_args (['- sum','1,'2,'3']) print (args) # result: Namespace (accumulate=, nums= [1,2,3]) # 4. Business logic result = args.accumulate (args.nums) print (result) # based on the above ['- sum','1,'2,'3'] parameters, accumulate is the sum function, and the result is 6

As you can see from the above example, we need to tell argparse exactly what the parameter looks like through add_argument:

Is it a position parameter nums or an option parameter-- sum

What is its type? for example, type=int indicates that the type is int

This parameter can be repeated several times, for example, nargs='+' indicates that at least 1

Parameter is stored or something, for example, action='store_const' represents a constant

It then parses the command-line arguments based on the given meta-information (that is, ['- sum','1,'2,'3'] in the example).

This is very computer thinking, although lengthy, but also brings flexibility.

2.2 、 docopt

From the concept of argparse, we can see that it is imperative. At this time, docopt takes a different approach. Is declarative also OK? The help information of a command-line program already contains the complete meta-information of the command line, so you can define the command line by defining help information? docopt is designed based on this idea.

The advantage of declarative is that as long as you master declarative syntax, it is easy to define meta-information on the command line.

The following example is a calculator program implemented by docopt:

# 1. Define interface description / help information "" Calculator Program. Usage: calculator.py [--sum]. Calculator.py (- h |-- help) Options:-h-- help Show help.-- sum Sum the nums (default: find the max). "" From docopt import docopt # 2. Parse the command line arguments = docopt (_ _ doc__, options_first=True, argv= ['--sum', '1percent,' 2percent,'3']) print (arguments) # result: {'--help': False,'--sum': True,'': ['1percent,' 2percent,'3']} # 3. Business logic nums = (int (num) for num in arguments [']) if arguments ['--sum']: result = sum (nums) else: result = max (nums) print (result) # based on the above ['- sum', '1arguments,' 2arguments,'3'] parameters, the processing function is sum function, and the result is 6

As you can see from the above example, we define the interface description through _ _ doc__, which is equivalent to add_argument in argparse, and then docopt converts the command line arguments to a dictionary based on this meta-information. This dictionary needs to be processed in the business logic.

Compare with argparse:

For more complex command programs, docopt is simpler in the definition of meta-information

However, in the processing of business logic, because argparse is more convenient in handling some simple parameters (such as the case in the example), the way in which docopt is converted into a dictionary and all the processing is handed over to business logic will be more complicated.

2.3 、 click

Command-line programs essentially define parameters and process parameters, and the logic of processing parameters must be associated with the defined parameters. Can functions and decorators be used to correlate processing parameter logic with defining parameters? And click is designed in this way.

The advantage of click's use of decorators is that they integrate parameter definition and processing logic with the elegant syntax of the decorator, thus implying routing relationships. Compared with argparse and docopt, it is much easier to do the routing relationship with the parsed parameters.

The following example is a calculator program implemented by click:

Import sys import click sys.argv = ['calculator.py','-sum','1','2','3'] # 2. Define the parameter @ click.command () @ click.argument ('nums', nargs=-1, type=int) @ click.option ('-- sum', 'use_sum', is_flag=True, help='sum the nums (default: find the max)') # 1. Business logic def calculator (nums, use_sum): "Calculator Program." Print (nums, use_sum) # output: (1, 2, 3) True if use_sum: result = sum (nums) else: result = max (nums) print (result) # based on the above ['- sum', '1arguments,' 2arguments,'3'] parameters, the handler function is sum function, and the result is 6 calculator ()

As can be seen from the above example, the parameters and the corresponding processing logic are well bound together, which looks intuitive, so that we can clearly understand how the parameters will be handled, which is especially important when there are a large number of parameters. Here is the most obvious advantage of click over argparse and docopt.

In addition, click also has a lot of built-in utilities and additional capabilities, such as Bash completion, color, paging support, progress bar and many other practical functions.

2.4 、 firefire

It is to play with the command line in a generalized object-oriented way, which can be classes, functions, dictionaries, lists, etc., which is more flexible and simpler. You do not need to define parameter types, fire will automatically determine based on input and parameter default values, which undoubtedly further simplifies the implementation process.

The following example is a calculator program implemented by fire:

Import sys import fire sys.argv = ['calculator.py',' 1,'2,'3,'--sum'] builtin_sum = sum # 1. Business logic # sum=False, implying that it is an option parameter-sum, or False # * nums if not provided, implying that it is a def calculator (sum=False, * nums) that can provide any number of location parameters: "Calculator Program." Print (sum, nums) # output: True (1,2,3) if sum: result = builtin_sum (nums) else: result = max (nums) print (result) # based on the above ['1values,' 2arguments, '3arguments,'-- sum'] parameters, the handler function is the sum function, and the result is 6 fire.Fire (calculator)

As you can see from the above examples, the approach provided by fire is undoubtedly the simplest and most Pythonic. We only need to focus on the business logic, while the definition of command line parameters is integrated with the definition of function parameters.

However, there are advantages and disadvantages, for example, nums does not say what type, which means that the input string 'abc' is also legal, which means that a strict command-line program must constrain the desired type in its own business logic.

Second, horizontal comparison

Finally, we horizontally compare the functions and features of the argparse, docopt, click, and fire libraries:

At this point, the study of "what library to use to write Python command line programs" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report