import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument('name', help="i can tell you how to set a name argument")
parser.parse_args()
1
2
3
4
$python main.py taylor -h
usage: main.py [-h] name
say something about this application !!
positional arguments:
name i can tell you how to set a name argument
optional arguments:
-h, --help show this help message and exit
1
2
3
4
5
6
7
8
9
10
11
可以看到name字段已经多了一个关于该字段的描述
好了现在可以考虑获取用户传入的值了
import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument('name', help="i can tell you how to set a name argument")
result = parser.parse_args()
import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument('name', help="i can tell you how to set a name argument")
result = parser.parse_args()
print(type(result.name))
1
2
3
4
5
6
$python main.py taylor
<type 'str'>
$python main.py 123456
<type 'str'>
import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument('name', type=int, help="i can tell you how to set a name argument")
result = parser.parse_args()
print(result.name)
print(type(result.name))
1
2
3
4
5
6
$python main.py taylor
usage: main.py [-h] name
main.py: error: argument name: invalid int value: 'taylor'
$python main.py 123456
123456
<type 'int'>
import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument("--age", help="this is an optional argument")
result = parser.parse_args()
print(result.age)
import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument("-a","--age", help="this is an optional argument")
result = parser.parse_args()
print(result.age)
import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument("-a", "--age", help="this is an optional argument", action="store_true")
result = parser.parse_args()
print(result.age)
import argparse
parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument("-a", "--age", help="this is an optional argument", type=int, choices=[0, 1, 2])
result = parser.parse_args()
print(result.age)