Examples of argparse module usage in python

Source: Internet
Author: User

Examples of argparse module usage in python

This example describes how to use the argparse module in python. Share it with you for your reference. The specific analysis is as follows:

Parameters are often included when writing a command line tool, so it is implemented using argparse in python.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

#-*-Coding: UTF-8 -*-

Import argparse

Args = "-f hello.txt-n 1 2 3-x 100-y B-z a-q hello @args.txt I _am_bar-h". split ()

# Use @ args.txt to require fromfile_prefix_chars = "@"

# In the args.txt file, you should have a line of parameters. For behavior changes, see convert_arg_line_to_args ()

# Brief description of ArgumentParser Parameters

# Description-The start Text of the command line help. In most cases, we only use this parameter

# Epilog-end Text of the command line help

# Prog-(default: sys. the name of the argv [0] program, which generally does not need to be modified. In addition, if you need to use the program name in help, you can use % (prog) s.

# Prefix_chars-command prefix. The default value is-, for example,-f/-- file. Some programs may want to support options such as/f. You can use prefix_chars = "/"

# Fromfile_prefix_chars-(default: None) It may be used if you want the command line parameters to be read from the file. For example, if fromfile_prefix_chars = '@', one of the command line parameters is "@args.txt", and the contents of args.txt are used as command line parameters.

# Add_help-whether to add the-h/-help option (default: True). Generally, the help information is required, so you do not need to set it.

# Parents-the type is list. If some parser options are the same as those of some other parser options, parents can be used for inheritance. For example, parents = [parent_parser]

# Formatter_class-custom help information format (description and epilog ). By default, long help information is <automatically wrapped and multiple consecutive white spaces are eliminated>.

# Three allowed values:

# Class argparse. RawDescriptionHelpFormatter directly outputs the original format of description and epilog (do not perform automatic line breaks or empty spaces)

# Class argparse. RawTextHelpFormatter directly outputs the original format of the description and epilog, and the help string in add_argument (do not perform automatic line breaks or empty spaces)

# Class argparse. argumentdefadefashelpformatter outputs their default values after the help information of each option, if any. This is the most common one!

# Argument_default-(default: None) sets the default value of a global option. Generally, each option is set separately, so this parameter is rarely used.

# Usage-(default: generated) if you need to modify the usage information (usage: PROG [-h] [-- foo [FOO] bar [bar...]), this can be modified. Do not modify it.

# Conflict_handler-not recommended. This is used in extreme cases. It is mainly used to define how the options added in the two add_argument statements are handled in case of a conflict of names. By default, an exception is thrown.

# Note A line ### common parameters

Parser = argparse. argumentParser (description = "This is a description of % (prog) s", epilog = "This is a epilog of % (prog) s", prefix_chars = "-+ ", fromfile_prefix_chars = "@", formatter_class = argparse. argumentdefashelshelpformatter)

# ArgumentParser. add_argument (name or flags... [, action] [, nargs] [, const] [, default] [, type] [, choices] [, required] [, help] [, metavar] [, dest])

# Add_argument parameters are complex...

# Name or flags-specify the parameter format and write a few values. However, we generally write two values: one short parameter and the other long parameter. For more information, see the following example: "-f ", "-- file"

# Optional options: the location is not fixed. You can write the data if you want to write the data. The default value is optional.

Parser. add_argument ("-f", "-- file", help = "test ")

# Fixed position options, such as "prog I _am_bar". In this case, I _am_bar is the value of the bar option, which is required by default.

Parser. add_argument ("bar", help = "test ")

# Nargs-specify the number of values after this parameter. For example, we want to use-n 1 2 3 4 to set the value of n to [1, 2, 3, 4].

Parser. add_argument ("-n", "-- num", nargs = "+", type = int)

# Here, nargs = "+" indicates that if you specify the-n option,-n must be followed by at least one parameter. + indicates at least one ,? Indicates one or zero, * zero or multiple,

# Default-if this option is not displayed in the command line, use the default value specified by default.

Parser. add_argument ("+ g", "++ gold", help = "test", default = "test_gold") # prefix_chars included "+"

# Type-if the parameter to be passed in is of the specified type (for example, float, int or file can be converted from a string), you can use

Parser. add_argument ("-x", type = int)

# Choices-set the parameter value range. If the type in choices is not a string, specify the type.

Parser. add_argument ("-y", choices = ['A', 'B', 'D'])

# Required-generally, options such as-f are optional, but if required = True, it is required.

Parser. add_argument ("-z", choices = ['A', 'B', 'D'], required = True)

# Metavar-parameter name, used only when the help information is displayed.

Parser. add_argument ("-o", metavar = "Oooooooo ")

# Help-set help information for this option

# Dest-set the value of this option to the attribute to which it is parsed.

Parser. add_argument ("-q", dest = "world ")

Args = parser. parse_args (args) # If you do not have the args parameter, use sys. argv, that is, the command line parameter. With this parameter, we can easily debug it.

# Args. world is the value of-q.

# Action-The basic type of action to be taken when this argument is encountered at the command line.

# Const-A constant value required by some action and nargs selections.

# These two help documents are complex.

# Http://docs.python.org/library/argparse.html

Print args

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.