怎么在运行python程序时,直接在命令行就指定一些参数呢?
转载一篇最近常观摩的文章。
原文出处:
内容如下。
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', action='store_true',
help="shows output")
args = parser.parse_args()
if args.output:
print("This is some output")
执行:
[ ]
[ ]
This is some output
[ ]
usage: optional_arg.py [-h] [-o]
optional_arg.py: error: argument -o/--output: ignored explicit argument 'utput'
[ ]
This is some output
[ ]
usage: optional_arg.py [-h] [-o]
optional arguments:
-h, --help show this help message and exit
-o, --output shows output
[ ]
usage: optional_arg.py [-h] [-o]
optional arguments:
-h, --help show this help message and exit
-o, --output shows output
#!/usr/bin/env python
import argparse
# required arg
parser = argparse.ArgumentParser()
parser.add_argument('--name', required=True)
args = parser.parse_args()
print(f'Hello {args.name}')
该示例必须指定name选项;否则失败
[root@localhost python]# python3 required_arg.py
usage: required_arg.py [-h] --name NAME
required_arg.py: error: the following arguments are required: --name
[root@localhost python]# python3 required_arg.py --name hugo
Hello hugo
#!/usr/bin/env python
import argparse
# positional args
parser = argparse.ArgumentParser()
parser.add_argument('name')
parser.add_argument('age')
args = parser.parse_args()
print(f'{args.name} is {args.age} years old')
执行:
[root@localhost python]# python3 positional_arg.py
usage: positional_arg.py [-h] name age
positional_arg.py: error: the following arguments are required: name, age
[root@localhost python]# python3 positional_arg.py hugo 24
hugo is 24 years old
#!/usr/bin/env python
import argparse
import datetime
# dest gives a different name to a flag
parser = argparse.ArgumentParser()
parser.add_argument('-n', dest='now', action='store_true', help="shows now")
args = parser.parse_args()
# we can refer to the flag
# by a new name
if args.now:
now = datetime.datetime.now()
print(f"Now: {now}")
执行:
dest.py -n
Now: 2019-03-22 17:37:40.406571
#!/usr/bin/env python
import argparse
import random
# type determines the type of the argument
parser = argparse.ArgumentParser()
parser.add_argument('-n', type=int, required=True,
help="define the number of random integers")
args = parser.parse_args()
n = args.n
for i in range(n):
print(random.randint(-100, 100))
执行:
$ rand_int.py -n 3
92
-61
-61
#!/usr/bin/env python
import argparse
# required defines a mandatory argument
# default defines a default value if not specified
parser = argparse.ArgumentParser()
parser.add_argument('-b', type=int, required=True, help="defines the base value")
parser.add_argument('-e', type=int, default=2, help="defines the exponent value")
args = parser.parse_args()
val = 1
base = args.b
exp = args.e
for i in range(exp):
val *= base
print(val)
该示例计算指数。不需要指数值;如果未给出,则默认值为 2。
执行:
power.py -b 3
9
power.py -b 3 -e 3
27
#!/usr/bin/env python
import argparse
# metavar gives name to the expected value
# in error and help outputs
parser = argparse.ArgumentParser()
parser.add_argument('-v', type=int, required=True, metavar='value',
help="computes cube for the given value")
args = parser.parse_args()
print(args)
val = args.v
print(val * val * val)
[ ]
usage: metavar.py [-h] -v value
metavar.py: error: the following arguments are required: -v
[ ]
usage: metavar.py [-h] -v value
optional arguments:
-h, --help show this help message and exit
-v value computes cube for the given value
[ ]
usage: metavar.py [-h] -v value
metavar.py: error: argument -v: expected one argument
[ ]
Namespace(v=3)
27
#!/usr/bin/env python
import argparse
# append action allows to group repeating
# options
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--name', dest='names', action='append',
help="provides names to greet")
args = parser.parse_args()
names = args.names
for name in names:
print(f'Hello {name}!')
[root@localhost python]# python3 appending.py 3
usage: appending.py [-h] [-n NAMES]
appending.py: error: unrecognized arguments: 3
[root@localhost python]# python3 appending.py -n Perter -n Lucy --name Jane
Hello Perter!
Hello Lucy!
Hello Jane!
#!/usr/bin/env python
import argparse
import sys
# nargs sets the required number of argument values
# metavar gives name to argument values in error and help output
parser = argparse.ArgumentParser()
parser.add_argument('chars', type=str, nargs=2, metavar='c',
help='starting and ending character')
args = parser.parse_args()
try:
v1 = ord(args.chars[0])
v2 = ord(args.chars[1])
except TypeError as e:
print('Error: arguments must be characters')
parser.print_help()
sys.exit(1)
if v1 > v2:
print('first letter must precede the second in alphabet')
parser.print_help()
sys.exit(1)
charseq.py e k
e f g h i j k
#!/usr/bin/env python
import argparse
# * nargs expects 0 or more arguments
parser = argparse.ArgumentParser()
parser.add_argument('num', type=int, nargs='*')
args = parser.parse_args()
print(f"The sum of values is {sum(args.num)}")
$ var_args.py 1 2 3 4 5
The sum of values is 15
#!/usr/bin/env python
import argparse
import datetime
import time
# choices limits argument values to the
# given list
parser = argparse.ArgumentParser()
parser.add_argument('--now', dest='format', choices=['std', 'iso', 'unix', 'tz'],
help="shows datetime in given format")
args = parser.parse_args()
fmt = args.format
if fmt == 'std':
print(datetime.date.today())
elif fmt == 'iso':
print(datetime.datetime.now().isoformat())
elif fmt == 'unix':
print(time.time())
elif fmt == 'tz':
print(datetime.datetime.now(datetime.timezone.utc))
[root@localhost python]# python3 mytime.py
[root@localhost python]# python3 mytime.py --now
usage: mytime.py [-h] [--now {std,iso,unix,tz}]
mytime.py: error: argument --now: expected one argument
[root@localhost python]# python3 mytime.py --now std
2021-11-08
[root@localhost python]# python3 mytime.py --now iso
2021-11-08T15:06:06.640909
[root@localhost python]# python3 mytime.py --now unix
1636355170.17874
[root@localhost python]# python3 mytime.py --now tz
2021-11-08 07:06:14.381828+00:00