我正在创建一个python脚本,并且为了解析我需要的参数: 该脚本将接受三个参数,只有一个是强制性的,第二个只是强制性的,这取决于第一个的某些值,第三个可能会出现也可能不出现。 这是我的尝试:
class pathAction(argparse.Action):
folder = {'remote':'/path1', 'projects':'/path2'}
def __call__(self, parser, args, values, option = None):
args.path = values
print "ferw %s " % args.component
if args.component=='hos' or args.component=='hcr':
print "rte %s" % args.path
if args.path and pathAction.folder.get(args.path):
args.path = pathAction.folder[args.path]
else:
parser.error("You must enter the folder you want to clean: available choices[remote, projects]")
def main():
try:
# Arguments parsing
parser = argparse.ArgumentParser(description="""This script will clean the old component files.""")
parser.add_argument("-c", "--component", help="component to clean", type=lowerit, choices=["hos", "hcr", "mdw", "gui"], required=True)
parser.add_argument("-p", "--path", help="path to clean", action = pathAction, choices = ["remote", "projects"])
parser.add_argument("-d", "--delete", help="parameter for deleting the files from the filesystem", nargs='*', default=True)
args = parser.parse_args()
如果效果很好,除了一个案例:如果我有-c它应该抱怨因为没有-p然而它没有 你能帮我吗? 感谢
答案 0 :(得分:1)
您可以添加一些自定义验证:
if args.component and not args.path:
parser.error('Your error message!')
答案 1 :(得分:0)
只有存在action
参数时,才会使用您的特殊-p
。如果您只是给它-c
,则从不使用交叉检查。
通常在parse_args
之后检查互动(建议为Gohn67
)比使用自定义操作更可靠,更简单。
如果您的命令行是'-p remote -c ...'
会怎样?在解析和设置pathAction
值之前,将调用-c
。那是你要的吗?只有在给出-p
时,您的特殊操作才有效,并且是最后一个参数。
另一个选择是让'component'成为subparser的位置。默认情况下,需要定位。可以将path
和delete
添加到需要它们的子分析器中。
import argparse
parser = argparse.ArgumentParser(description="""This script will clean the old component files.""")
p1 = argparse.ArgumentParser(add_help=False)
p1.add_argument("path", help="path to clean", choices = ["remote", "projects"])
p2 = argparse.ArgumentParser(add_help=False)
p2.add_argument("-d", "--delete", help="parameter for deleting the files from the filesystem", nargs='*', default=True)
sp = parser.add_subparsers(dest='component',description="component to clean")
sp.add_parser('hos', parents=[p1,p2])
sp.add_parser('hcr', parents=[p1,p2])
sp.add_parser('mdw', parents=[p2])
sp.add_parser('gui', parents=[p2])
print parser.parse_args()
样本使用:
1848:~/mypy$ python2.7 stack21625446.py hos remote -d 1 2 3
Namespace(component='hos', delete=['1', '2', '3'], path='remote')
我使用parents
来简化向多个子分析器添加参数的过程。我使path
成为一个位置,因为它是必需的(对于2个子分析符)。在这些情况下,--path
只会让用户输入更多内容。使用nargs='*'
时,--delete
必须属于子分析符,因此它可以最后出现。如果nargs
已修复(None
或数字),则可能是parser
的参数。