Python Parse Console Input

Abstract:

This page try to describe the basic function of argparse, which handle the input argument well.
argparse is included in python package. We can import it directly.

Content:

As it’s quite simple and useful for coding, I just give a short example to show the most common usage. You could add different types of arguments by add_argument.

Basic Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# import module
import argparse as arg
# init parser object
parser = arg.ArgumentParser(description='Calculate the exponent of given number, sample to practise argparse')
# add one int type argument
parser.add_argument("testflag", type=int, help="display the test")
# add a list of arguments and store as int list
parser.add_argument("-l", "--list", type=int, help="given number and power", required=True, nargs='+')
# add a another int type argument that can only be of the choices
parser.add_argument("-v", "--verbosity", type=int, choices=[0,1], help="increate output verbosity", default=0)
# add a flag only argument to store true or false
parser.add_argument('-f', '--force', action='store_true', help="force to update golden without asking user")
# parse all arguments from command line
args, unknownargs = parser.parse_known_args()

#answer=args.testflag**2
if args.testflag==1:
print("test success")
list=args.list;
answer=list[0]**list[1]
if args.verbosity==1:
print"the number {0} power {1} is {2}".format(list[0], list[1], answer)
else:
print(answer)

Tricks

Usally, when we apply argpare, it means we what some input from command line. But it’s quite unconvinient in developing or debug process. Besides, if you want it could be both command line entrance or importable interface, argparse also provide this option.

1
2
3
4
5
6
def main(arg_input=None):
if arg_input:
args, unknownargs = parser.parse_known_args(arg_input.split())
else:
args, unknownargs = parser.parse_known_args()
return args, unknownargs

Now, you can either treat it as command line entrance and input argument from command line by invoke main(), or you can use it as interface by transferring all the arguments to a function argument as string type, such as main("--list 1 2 -f").

History:

  • 2016-09-11: 将内容记录下来
  • 2016-11-06: finish the coding(can’t input Chinise now~~)
  • 2019-02-06: add tricks to input from non command line