使用ArgPars解析python的参数

2024-10-03 17:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个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,但它没有 你能帮帮我吗? 谢谢


Tags: thetopathcleanaddparser参数remote
2条回答

只有存在-p参数时,才会使用特殊的action。如果只给它一个-c,则不会使用交叉检查。在

一般来说,检查parse_args(正如Gohn67所建议的那样)之后的交互比使用自定义操作更可靠、更简单。在

如果命令行是'-p remote -c ...',会发生什么情况?pathAction将在解析并设置-c值之前调用。这就是你想要的吗?只有在给定-p并且是最后一个参数时,您的特殊操作才有效。在


另一个选择是将“组件”设为一个辅助位置。默认情况下,位置是必需的。path和{}可以添加到需要它们的子parser中。在

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()

样品使用:

^{pr2}$

我使用parents来简化向多个子parser添加参数的过程。我将path设置为一个位置,因为它是必需的(对于2个子parser)。在这些情况下, path只会让用户输入更多。对于nargs='*' delete必须属于子parser,这样它才能最后出现。如果它的nargs是固定的(None或数字),那么它可能是parser的一个参数。在

您可以添加一些自定义验证,如下所示:

if args.component and not args.path:
    parser.error('Your error message!')

相关问题 更多 >