【问题标题】:Argument parsing python using ArgParse使用 ArgParse 解析 python 的参数
【发布时间】:2014-03-04 17:29:42
【问题描述】:

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

【问题讨论】:

标签: python parsing python-2.7 argparse


【解决方案1】:

您可以像这样添加一些自定义验证:

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

【讨论】:

  • 否,因为 args.path 将取决于 args.component 的某些值,实际上应该始终输入 args.component.. 任何线索??
【解决方案2】:

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

通常检查parse_args 之后的交互(如Gohn67 建议的那样)比使用自定义操作更可靠、更简单。

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


另一种选择是使“组件”成为子解析器位置。默认情况下需要定位。 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()

示例使用:

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 的参数。

【讨论】:

  • 这个解决方案对我的目的来说似乎很好。非常感谢!
猜你喜欢
  • 2018-12-14
  • 2015-03-04
  • 2016-05-30
  • 1970-01-01
  • 2014-05-20
  • 2015-07-20
  • 2013-09-13
  • 1970-01-01
相关资源
最近更新 更多