简体   繁体   English

使用ArgParse解析python的参数

[英]Argument parsing python using ArgParse

I am creating a python script and for parsing the arguments I would need this: the script will accept three parameters, only one always mandatory, the second one will only be mandatory depending on certain values of the first one and the third one may or may not appear. 我正在创建一个python脚本,并且需要解析参数:脚本将接受三个参数,只有一个始终是强制性的,第二个将仅是强制性的,具体取决于第一个和第三个的某些值。没有出现。 This is my try: 这是我的尝试:

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

if works well except one case: if i have -c it should complain because there is no -p however it does not Can you help me please? 如果除一种情况下工作正常:如果我有-c,则应该投诉,因为没有-p,但是没有,您能帮我吗? Thanks 谢谢

You can add some custom validation like this: 您可以添加一些自定义验证,如下所示:

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

Your special action will be used only if there is a -p argument. 仅当存在-p参数时,才会使用您的特殊action If you just give it a -c the cross check is never used. 如果只给它-c ,则从不使用交叉检查。

Generally checking for interactions after parse_args (as Gohn67 suggested) is more reliable, and simpler than with custom actions. 通常,检查parse_args之后的parse_args (如Gohn67建议的)比使用自定义操作更可靠,更简单。

What happens if your commandline was '-p remote -c ...' ? 如果您的命令行是'-p remote -c ...'会发生什么? pathAction would be called before the -c value is parsed and set. 将在解析和设置-c值之前调用pathAction Is that what you want? 那是你要的吗? Your special action only works if -p is given, and is the last argument. 仅当给出-p且它是最后一个参数时,您的特殊操作才有效。


Another option is to make 'component' a subparser positional. 另一种选择是使“组件”成为子解析器的位置。 By default positionals are required. 默认情况下,需要位置。 path and delete can be added to those subparsers that need them. 可以将pathdelete添加到需要它们的那些子解析器中。

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

sample use: 样品使用:

1848:~/mypy$ python2.7 stack21625446.py hos remote -d 1 2 3
Namespace(component='hos', delete=['1', '2', '3'], path='remote')

I used parents to simplify adding arguments to multiple subparsers. 我使用parents简化了向多个子解析器添加参数的过程。 I made path a positional, since it is required (for 2 of the subparsers). 我将path定位,因为这是必需的(对于2个子解析器)。 In those cases --path just makes the user type more. 在这种情况下,-- --path只会使用户键入更多内容。 With nargs='*' , --delete has to belong to the subparsers so it can occur last. 随着nargs='*'--delete有属于subparsers所以它可以发生最后一次。 If it's nargs was fixed ( None or number) it could be an argument of parser . 如果nargs是固定的( None或number),则可能是parser的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM