Python argparse required=True 但 --version 功能? [英] Python argparse required=True but --version functionality?
问题描述
在我的所有脚本中,我使用标准标志 --help
和 --version
,但是我似乎无法弄清楚如何制作 --版本
with parser.add_argument(..., required=True)
.
In all my scripts I use the standard flags --help
and --version
, however I cannot seem to figure out how to make a --version
with parser.add_argument(..., required=True)
.
import sys, os, argparse
parser = argparse.ArgumentParser(description='How to get --version to work?')
parser.add_argument('--version', action='store_true',
help='print version information')
parser.add_argument('-H', '--hostname', dest='hostname', required=True,
help='Host name, IP Address')
parser.add_argument('-d', '--database', dest='database', required=True,
help='Check database with indicated name')
parser.add_argument('-u', '--username', dest='username', required=True,
help='connect using the indicated username')
parser.add_argument('-p', '--password', dest='password', required=True,
help='use the password to authenticate the connection')
args = parser.parse_args()
if args.version == True:
print 'Version information here'
$ ./arg.py --version
usage: arg.py [-h] [--version] -H HOSTNAME -d DATABASE -u USERNAME -p PASSWORD
arg.py: error: argument -H/--hostname is required
是的,我希望 --hostname
和其他是必需的,但我总是希望 --version
像 --help
(和 -h
)一样适当地工作.
Yes, I want --hostname
and others required, but I always want --version
to work appropriately like --help
(and -h
).
$ ./arg.py --help
usage: arg.py [-h] [--version] -H HOSTNAME -d DATABASE -u USERNAME -p PASSWORD
How to get --version to work?
optional arguments:
-h, --help show this help message and exit
--version print version information
-H HOSTNAME, --hostname HOSTNAME
Host name, IP Address
-d DATABASE, --database DATABASE
Check database with indicated name
-u USERNAME, --username USERNAME
connect using the indicated username
-p PASSWORD, --password PASSWORD
use the password to authenticate the connection
对让 --version
工作有什么帮助吗?
Any help on getting --version
to work?
推荐答案
add_argument
有一个特殊的version action
关键字参数(如此处记录:argparse#action).
试试这个(从工作代码复制):
There is a special version action
keyword argument to add_argument
(As documented here: argparse#action).
Try this (copied from working code):
parser.add_argument('-V', '--version',
action='version',
version='%(prog)s (version 0.1)')
这篇关于Python argparse required=True 但 --version 功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!