For python command line, you should do so only professional

On hardship

Talking with friends, when it comes to the issue of learning. I do not know when heard a word, because do not want to eat bitter life, so I endured the pain of learning. Bitter life lying just be able to eat, but we have to learn bitter forced himself to eat. Wait until the children came home from work every day to sleep begin to learn, to learn about it before you start a blog, and then made public number, two or three every day to make the body too much for some recent, light take the shuttle bus station slept like a few times, the drivers now know me , the first call my arrival. Arrogant ... No pain is not necessarily there will be a harvest, but want something to rely on ongoing efforts ... have a chance to pay!
Yesterday it python string associated methods are summarized, saying too many points to be honest fragmentary knowledge, statistics, classification, sorting, description of the last one took more than two hours of time. But go over the whole string of previous knowledge has conducted a leak filled, Reviewing the Old, not bad ...
today, and we talk about the python command line arguments, although the scene is no more than a string, but the details that success or failure when people see you calling to provide a more elegant way, would you like rigor point. At this point, deep reactive with the name! Shengtang ...

python command line arguments

In python development, we often encounter in the implementation of .py files, you need to case the code parameter passing.
Encountered parameter passing scene, the most basic way to pass parameters *.py argv1 argv2 ..., and then we come to the Senate resolved by sya.argv code.
Such use is no problem, but not rigorous, not formal, more handsome ... who know you enough of these parameters is doing?
In fact, sys.argv python-based command-line argument, there are three modules getopt -> optprase -> argprase. Today, we say it in the command line module peak argprase!

Started five tricks

# -*- coding: utf-8 -*-
# @Author   : 王翔
# @JianShu  : 清风Python
# @Date     : 2019/6/25 23:58
# @Software : PyCharm
# @version  :Python 3.7.3
# @File     : 11.python_argparse_cookbook.py

# 导入模块
import argparse

# 实例化解析器对象
parser = argparse.ArgumentParser(description='python argparse cookbook')
# 添加参数
parser.add_argument('-v', '--version', help="get version")

# 获取参数集合
args = parser.parse_args()

# 打印参数值
print("User input code version is: {}".format(args.version))

About ArgumentParser

ArgumentParser used to create a parser object, it provides a number of optional parameters:

Object for parsing command line strings into Python objects.
Keyword Arguments:

  • prog -- The name of the program (default: sys.argv[0])

  • usage -- A usage message (default: auto-generated from arguments)

  • description -- A description of what the program does

  • epilog -- Text following the argument descriptions

  • parents -- Parsers whose arguments should be copied into this one

  • formatter_class -- HelpFormatter class for printing help messages

  • prefix_chars -- Characters that prefix optional arguments

  • fromfile_prefix_chars -- Characters that prefix files containing
    additional arguments

  • argument_default -- The default value for all arguments

  • conflict_handler -- String indicating how to handle conflicts

  • add_help -- Add a -h/-help option

  • allow_abbrev -- Allow long options to be abbreviated unambiguously

In which the description is used to add a description of the program, more use, the other as you can understand:

  • prog - name of the program (default: sys.argv [0])

  • usage - usage string describing the program (default: generate from the parameter parser)

  • description - parameter text before help information (default: empty)

  • epilog - text parameter after the help information (default: empty)

  • parents - ArgumentParser a list of objects, the parameters of these objects should be included

  • formatter_class - customized help classes

  • prefix_chars - prefix characters set optional parameters (default: '-')

  • fromfile_prefix_chars - Prefix character set file additional parameters to be read (default: None)

  • argument_default - global default value for the parameter (default: None)

  • conflict_handler - strategy to solve the conflict of optional parameters (usually not necessary)

  • add_help - Add to the parser -h / -help option (default: True)

Essence: add_argument

add_argument As the highlight of the entire module, we need careful study.
Complete the following format:
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

  • name or flags - the name of a string or a list of options, such as foo or -f, --foo.

  • action - the action command-line parameters when encountered, the default is store.

  • nargs - the number of command line parameters to be read, can be a specific number, or a number, when no value is specified for use default Positional argument, for Optional - - - argument used const;?, or asterisk, represent 0 or more parameters; a + sign or 1 or more parameters.

  • const - action and nargs needed constant value.

  • default - the default when no argument.

  • type - the type of command-line arguments should be converted into.

  • choices - a container permissible parameter values.

  • required - whether optional parameters can be omitted (only for optional parameters).

  • help - help parameters, said they did not display help information on this parameter when specified as argparse.SUPPRESS.

  • metavar - Parameter name usage instructions, for the mandatory parameter is the default parameter name, the default parameter is optional for parameter names in all uppercase letters.

  • dest - Parameter resolved name, default parameters for the selected optional longest name, is converted to an underscore underlined.
    add_argument for adding the reference, which is divided into location parameters and optional parameters, how the difference?

Alignment Parameters

For example, we must require each program to enter a user name, then we can write:

import argparse

parser = argparse.ArgumentParser(description='python argparse cookbook')

parser.add_argument('user', help="input username")
parser.add_argument('pwd', help="input password")
parser.add_argument('-v', '--version', help="get version")

args = parser.parse_args()

print(args.user)
if args.version:
    print(args.version)

So we can enter:

  • a.py qingfeng 123

  • a.py qingfeng 123 -v 1.0

  • a.py -v 1.0 qingfeng 123

  • a.py 123 -v 1.0 qingfeng # Note that this

Positioning parameters can be used, but the best in your code, there is only one positional parameter, otherwise the problem will be the last example, you only have to ask me to input parameters, and does not require my input sequence. In this case we might as well use the optional parameter to specify ** - u -p ** be more intuitive, no reasonable?

Optional parameters

What is an optional parameter? To add a dash or two of the add_argument "-" in the beginning of the parameter is optional (provided that you are bored to modify the parameters prefix_chars ArgumentParser in). eg: '- v' or '--version'.
These two optional parameters should be paid is that if there is at the same time and -v --version. Users can use any way to pass parameters, but when we get the parameters, can only be used args.versionin order to obtain the corresponding value.

action='store_true'

We usually use the command-line parameters, some parameters without having to pass values, such as the most simple ls -l.
But if so, the system will complain ah. What to do?
parser.add_argument('-v', '--version', action='store_true', help="get version")
We only need to action assignment store_true, you can.

The default value of the parameter

When we add a parameter by add_argument, parser.parse_args () will be in a corresponding initialization parameters, and assignments.
The default is None. The above said action = 'store_true', the default parameter is False.
Of course, we can change the default None by default to the value we want

Parameter limits

The use of more, such as our code, provides tools for installation, uninstallation, start, stop and other functions. We can operate ... so
parser.add_argument('-t', '--type', choices=['install','uninstall','start','stop'])
the user can fill out the choices by internal command -t, or will be prompted invalid choice: the parameter error
As another example, we need a program to provide users with information on a port, the port must be a number. For the use of the port is a number, we can get the parameters isinstance (port, int) to judge, but this is equivalent to re-create the wheels, argparse provide a type options, the user can enter parameters, calibration directly, without the need you then secondary judgment! demo:
parser.add_argument('-p', '--port', type=int)
When we enter -p abc, the module will prompt: error: argument -p / - Port: int invalid value: 'ABC'

The optional parameter becomes mandatory

It is actually very simple:
parser.add_argument('-u','--user',required=True,help="input username")
if it is to fill in the parameters, you will be prompted: at The arguments The following are required: -u / - the User

The End

Some people might say, selenium series is not a eunuch, can only say that this series too few people to see, the time interval with the update it ...
the OK, today's content on here, if that helps, welcome the articles or my micro-channel public number 【清风Python】to share with more people like python, thank you.

Source: breeze Python Author: Wang Xiang 

Guess you like

Origin blog.csdn.net/devcloud/article/details/94599353