SoFunction
Updated on 2024-11-17

An introduction to simple command line tools for python development

present (sb for a job etc)

The Python module argparse, an interpreter of command line options, arguments, and subcommands, allows you to write user-friendly command line tools. argparse will figure out how to parse the arguments in a program that defines the arguments you need. argparse also supports automatic generation of help and usage information, and can issue an error when it parses an invalid argument. When the module parses an invalid parameter, it can also issue an error.

python standard library sys module

				# Command line parameter List, the first element is the path to the program itself.
(n)		# Exit the program, exit(0) on normal exit.
 	# Get the version information of the Python interpreter program
 		# Maximum Int value
			# Returns the search path of the module, initialized with the value of the PYTHONPATH environment variable.
			# Input line pipe
		#Output related
	#Error related

command-line tool

We have used a lot of command line tools, so what are some of the command line tools that python has developed that can be listed?
In fact, python itself is a command line tool. Using python --help in cmd can output python help statements, which is an example of what a command line tool outputs after parsing arguments.
Again, pip is a classic example of how different subcommands can achieve different results when using pip.
Of course knowing and doing are just too far apart, and I'd be hard pressed to write a python or pip.

conceptual

argparse is a larger module that provides a lot of functionality, and its documentation is quite detailed and complete, containing tons of examples. So the best tutorial to learn this module is the official documentation, argparse( /zh-cn/3/library/),So why I didn't go through it, on the one hand I don't need complex features, on the other hand my English reading skills are not good enough for me to fully understand the document. We must admit that the English level separates the average technician, so I am trying to improve my English.
Before developing a command line tool, we first need to know what a command line tool contains, and how it recognizes the arguments we provide, and how it provides output after recognizing them, and how it adjusts to treat wrong options.
Therefore, the official website uses the command 'ls' to introduce several concepts of command line tools:

  • ls is a very useful command even if it is run with no options provided. By default he outputs what the current folder includes.
  • If we want to use more features than it provides by default, we need to tell the command more information. We can specify what is called a positional parameter, so named because what the program should do with the value of that parameter depends entirely on the context in which it appears on the command line. Commands that better exemplify this concept are commands such as cp, which in its most basic usage iscp SRC DESTThe first position parameter refers to the one you want to copy to, and the second position parameter refers to the one you want to copy to.
  • Now suppose we want to change the behavior of this program. Using **ls -l,** we can output more information, in this case -l is called an optional parameter.
  • **-help ** is often used to output help documentation, and it is very useful because when you come across a program you've never used before, you can figure out how it works by reading its help documentation.

Knowing this, let's go through a few examples to better illustrate how this module parses parameters obtained from the command line and how the parsed parameters are used by the program.

infrastructural

Command line parameter parsing is easy, but it can also be augmented with a lot of parameters and injected with a lot of definitions, which makes the final program unwieldy, and to prevent a headache at the start for my friend, that's you, I'll start by bringing in what I think is the simplest case.

typical example

All parses should be accompanied by examples and comparisons should be shown to illustrate how the behavior of the program has changed.

There are four main steps in argparse usage:

  • Importing the argparse package
  • Creating the ArgumentParser() parameter object
  • Call the add_argument() method to add an argument to the argument object.
  • Use parse_args() to parse the parameter object of the added argument to get the parsed object
  • The rest of the program uses the parsing object when command line arguments are required. Getting Parameters

Before using the argparse module, I wrote this python file.

print("hello world!")

We're familiar with this case, and no doubt we know exactly what kind of output we'll get when python runs the file, and when we run this python file demo1 in the terminal, we'll use the following command.

$ python 
hello world!

Yes, we see that in the command line, running the file outputs the result we want, normally, when we need a python file to output a certain value, either we write that value dead in the file, as in the example above, we have already written the desired output dead in the file, and that value is already decided in the program when it is not being output. If we need the user to provide some value to the program in the terminal to change the program's behavior and get a different output, a common means of doing this is to use input, which allows the program to read the terminal's input to achieve this effect. However, this still requires manual input, and in the case of automated programs, the ability to use parameters to bring in the desired variables directly will greatly reduce this interaction.
Next I'll show how to use argparse to accomplish a simple parameter parsing.

import argparse # Import the argparse package

parse = () # Create parameter objects
parse.add_argument('hello') # Add parameters to the parameter object
args = parse.parse_args() # Parse parameter objects to get parsed objects
if __name__ == '__main__':
   print()

Let's run the program.

$ python  helloworld
helloworld

It's easy, this is an easy example, it should be noted that since it is not specified, the command line parameter inputs are copied in order by default, and you will get different results if the order is different.
Next I'll bring in some official website examples to continue explaining some advanced examples of argparse.

Introduction to use

  • The -help option, which can also be abbreviated as -h, is the only option that can be used directly (i.e., there is no need to specify the contents of the option). Specifying anything will result in an error. Even so, we get a useful piece of usage information straight away.

The add_argument() method, which defines how to parse command line arguments, for which the arguments are explained as follows.

  • name or flags - The name or list of option strings, such as foo or -f, --foo.
  • action - The action to take when the command line encounters the argument, the default value is store.
    • store_const, indicating that the assignment is const;
  • - append, which stores the encountered values as a list, i.e. multiple values if the arguments are repeated; the
  • - append_const to save a value defined in the parameter specification to a list;
  • - count, which stores the number of encounters; in addition, it can be inherited for custom parameter parsing;
  • nargs - the number of command line arguments that should be read, can be
  • A specific number, or ? sign, use default for Positional argument and const for Optional argument when no value is specified.
  • or the * symbol for 0 or more parameters;
  • Or the + sign indicates 1 or more parameters.
  • const - Constant values required for action and nargs.
  • default - The default value when no parameters are specified.
  • type - The type to which command line arguments should be converted.
  • choices - A container for the allowable values of the parameter.
  • required - whether optional parameters can be omitted (optional parameters only).
  • help - help information for the parameter, when specified as means do not show help information for this parameter.
  • metavar - the name of the parameter in the usage description, defaults to the parameter name for mandatory parameters, defaults to the parameter name in all uppercase for optional parameters.
  • dest - the name of the parsed parameter, by default the longest name is selected for optional parameters, underscores are converted to underscores.

Optional parameter settings

By prefixing the parameter name with--, is set as an optional parameter, and if not entered, thedefaultDefault value, if setdefaultis assigned by defaultNone

parse.add_argument('-n', '--name', type=str, metavar='name', help='New flavor name')

Reference names, which shorten parameter names and simplify command line parameter entry; that is, you can use -n or -name to obtain the same effect

Mandatory parameter settings

When a mandatory parameter is required, set therequired=True, in this case, regardless of whether the parameter is optional or not, you must enter the

List parameter incoming settings

increasenarg='+' This allows several arguments to be added to the command line, which will be added to the list when passed in.

mutually exclusive parameter

i.e.add_mutually_exclusive_groupmethod, which allows us to add two mutually exclusive parameters, i.e. only one of them can be selected to add the

Default Parameter Settings

set_defaults() allows you to set the default values of some parameters

to this article on the development of simple python command-line tools Introduction to this article, more related python development of simple command-line tools content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!