Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ArgParse解析python的参数_Python_Parsing_Python 2.7_Argparse - Fatal编程技术网

使用ArgParse解析python的参数

使用ArgParse解析python的参数,python,parsing,python-2.7,argparse,Python,Parsing,Python 2.7,Argparse,我正在创建一个python脚本,为了解析参数,我需要: 脚本将接受三个参数,只有一个始终是必需的,第二个参数将仅是必需的,具体取决于第一个参数的某些值,第三个参数可能会出现,也可能不会出现。 这是我的尝试: class pathAction(argparse.Action): folder = {'remote':'/path1', 'projects':'/path2'} def __call__(self, parser, args, values, option = None):

我正在创建一个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()  
if工作得很好,除了一个例子:如果我有-c,它应该抱怨,因为没有-p,但它没有 你能帮我吗?
谢谢

您可以添加如下自定义验证:

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

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

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

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


另一个选项是将“组件”设置为子Parser位置。默认情况下,位置是必需的<代码>路径和
删除
可以添加到需要它们的子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()
样本使用:

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

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

的一个参数,因为args.path将取决于args.component的某些值,实际上args.component应该始终输入。。有什么线索吗?这个解决方案对我来说太好了。非常感谢你!