Command line parsing function

sys.argv

In the terminal run python 1.py hahah

import sys 

print(sys.argv)    # ['1.py', 'hahah']

argparse

  Python command-line parsing module, which is a python's built-in library, through the program we defined parameters, argparse will sys.argv parsed out from these parameters, and automatically generate help and usage information.

Simple use of argparse

  • Creating ArgumentParser () Object
  • Call add_argument () method to add parameters
  • Use parse_args () parameter parsing added
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('integer', type=int, help='display an integer')
args = parser.parse_args()

print(args.integer)

Save the above code file  argparse_usage.py, running in the terminal, as follows:

$ python argparse_usage.py
  usage: argparse_usage.py [-h] integer
  argparse_usage.py: error: too few arguments

$ python argparse_usage.py abcd
  usage: argparse_usage.py [-h] integer
  argparse_usage.py: error: argument integer: invalid int value: 'abcd'

$ python argparse_usage.py -h
  usage: argparse_usage.py [-h] integer

  positional arguments:
    integer     display an integer

  optional arguments:
    -h, --help  show this help message and exit

$ python argparse_usage.py 10
  10

Alignment Parameters

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number", type=int)
args = parser.parse_args()
print(args.square**2)

Save the above code file  argparse_usage.py, running in the terminal, as follows:

$ python argparse_usage.py 9
  81

Optional parameters

Optional parameter is the command-line argument is optional

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--square", help="display a square of a given number", type=int)
parser.add_argument("--cubic", help="display a cubic of a given number", type=int)

args = parser.parse_args()

if args.square:
    print args.square**2

if args.cubic:
    print args.cubic**3

Save the above code file  argparse_usage.py, running in the terminal, as follows:

$ python argparse_usage.py --h
  usage: argparse_usage.py [-h] [--square SQUARE] [--cubic CUBIC]

  optional arguments:
    -h, --help       show this help message and exit
    --square SQUARE  display a square of a given number
    --cubic CUBIC    display a cubic of a given number

$ python argparse_usage.py --square 8
    64

$ python argparse_usage.py --cubic 8
    512

$ python argparse_usage.py 8
    usage: argparse_usage.py [-h] [--square SQUARE] [--cubic CUBIC]
    argparse_usage.py: error: unrecognized arguments: 8

$ Python argparse_usage.py   # no output

Mixed use

Location parameter options and parameters can be mixed, a look at the following example, given a sequence of integers, or the output thereof and a maximum value (default):

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Save the above code file  argparse_usage.py, running in the terminal, as follows:

$ python argparse_usage.py
  usage: argparse_usage.py [-h] [--sum] N [N ...]
  argparse_usage.py: error: too few arguments
$ python argparse_usage.py 1 2 3 4
  4
$ python argparse_usage.py 1 2 3 4 --sum
  10

add_argument () method

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

Each parameter explained as follows:

  • 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.
    • store_const, expressed assigned const; store_ture / store_false. See below for details.
    • store_const, expressed assigned const; store_ture / store_false. See below for details.
    • append, the value is stored as a list encountered, if the parameter is repetition will hold multiple values;
    • append_const, to save a value of the parameter defined in the specification to a list;
    • count, count storage encountered; moreover, it can be inherited argparse.Action custom parameter analysis;
  • const - action and nargs needed constant value.
  • nargs - the number of rows to be read command parameters may be specific numbers or number, when no value is specified for use default Positional argument, for use Optional argument const; or asterisk, represent 0 or more? parameter; + sign or 1 or more parameters.
  • 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 parameter, when assigned to   represent hide the help of the parameters at the time.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, underlined converted to underscores.
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--inter', action='store_true')
args = parser.parse_args()

print(args.interpolate)

In the command line to run Python temp.py           args.interpolate is False

In the command line to run Python temp.py --inter     args.interpolate is True

tensorflow learning (c) the use of flags defined command-line arguments

tensorflow use command-line arguments

1, tf.app.flags () # He supported the application accepts the following parameters define the parameters of the type in the command line tf.app.flags

DEFING_string(flag_name, default_value, docstring)

DEFING_integer(flag_name, default_value, docstring)

DEFING_boolean(flag_name, default_value, docstring)

DEFING_float(flag_name, default_value, docstring)

2, tf.app.flags, there is a flag in FLAGS Flags, he can call our previously defined flag_name in the program,

3, starting maini (argv) function by tf.app.run ()

tf.app.flags.DEFINE_integer ( " MAX_STEP " , 0, " the number of steps of the training model " )
tf.app.flads.DEFINE_string ( " model_dir " , "" , " save the model path model name + " )
The FLAGS = tf.app.flags.FLAGS  # custom command line parameter 
Print (FLAGS.max_step)
 Print (FLAGS.model_dir)
 DEF main (the argv):
  Print (the argv)
tf.app.run ()  # start the main function

 

Guess you like

Origin www.cnblogs.com/LXP-Never/p/11093896.html