Python 验证一个论点而不是另一个论点

Python 验证一个论点而不是另一个论点,python,argparse,Python,Argparse,我有两个附加选项,我需要验证第二个选项,并考虑第一个选项 我试过这个: #!/bin/env python3 # -*- coding: utf-8 -*- from argparse import ArgumentParser, ArgumentTypeError from os import getenv, path def invalidArgument(value, text= None): raise ArgumentTypeError("%s %s" % (value,

我有两个附加选项,我需要验证第二个选项,并考虑第一个选项

我试过这个:

#!/bin/env python3
# -*- coding: utf-8 -*-

from argparse import ArgumentParser, ArgumentTypeError
from os import getenv, path

def invalidArgument(value, text= None):
    raise ArgumentTypeError("%s %s" % (value, text))

def directory(value):
    if path.isdir(value):
        return value
    invalidArgument(value, "directory not found")

def parsing():
    parser= ArgumentParser("")
    parser.add_argument("-dir", type= directory, action= "store", default= "/home", help= "Base directory")
    parser.add_argument("-loc", action= "store_true", help= "Takes into account locale")
    namespace, other= parser.parse_known_args()
    if namespace.loc:
        l= getenv("LANG", "en")[0:2].lower()
        if l == "en":
            namespace.loc= False
        else:
            if path.isdir(path.join(namespace.dir, l)):
                namespace.loc= path.join(namespace.dir, l)
            else:
                invalidArgument(path.join(namespace.dir, l), "directory not found $LANG not valid")
    return namespace, other

if __name__ == "__main__":
    namespace, other= parsing()
    print("Base directory:", namespace.dir)
    print("Locale directory:", namespace.loc)
我得到(使用./tst.py-loc):

我需要:

Base directory: /home
Locale directory: False
Base directory: /home
Locale directory: /home/fr
Base directory: /home/foo
Locale directory: /home/foo/fr
如果我打电话给:

./tst.py
./tst.py -loc
./tst.py -dir=/home/foo -loc
我需要:

Base directory: /home
Locale directory: False
Base directory: /home
Locale directory: /home/fr
Base directory: /home/foo
Locale directory: /home/foo/fr
如果我打电话给:

./tst.py
./tst.py -loc
./tst.py -dir=/home/foo -loc
我需要:

Base directory: /home
Locale directory: False
Base directory: /home
Locale directory: /home/fr
Base directory: /home/foo
Locale directory: /home/foo/fr

有人对我有什么想法或想法吗?

您可以使用带一个破折号的单字母参数,以及带两个破折号的多字母参数:
-h、 --help

如果
/fr
目录不存在,则错误消息有意义

如果您想要一条包含用法和退出的错误消息,请使用
parser.error(…)
,而不仅仅是引发异常

我已经简化了您的代码,部分是为了适应常见的argparse用法,但更重要的是要关注正确的解析。因为我的语言是“恩”,所以我参加了那部分测试。在这一点上,测试特定目录是一种干扰

我认为您的主要问题是
type=directory
参数。该参数应该是一个函数,它接受一个字符串并返回任何内容。它不指定所需对象的类型。由于没有
目录(asr)
功能,该步骤失败

def parsing():
    parser= ArgumentParser(prog='PROG')
    parser.add_argument('-d',"--dir", default= "/home", help= "Base directory")
    parser.add_argument('-l',"--loc", action= "store_true", help= "Takes into account locale")
    namespace, other= parser.parse_known_args()

    if namespace.loc:
        l = 'fr'
        namespace.loc= path.join(namespace.dir, l)
    return namespace, other
各种测试包括:

1139:~/mypy$ python3 stack29283397.py
Base directory: /home
Locale directory: False
1144:~/mypy$ python3 stack29283397.py -l
Base directory: /home
Locale directory: /home/fr
1144:~/mypy$ python3 stack29283397.py --dir=/home/foo -l
Base directory: /home/foo
Locale directory: /home/foo/fr
loc
测试更改为:

if namespace.loc:
    l = 'fr'
    namespace.loc= path.join(namespace.dir, l)
    parser.error('%s directory not found'%namespace.loc)
产生:

1145:~/mypy$ python3 stack29283397.py --dir=/home/foo -l
usage: PROG [-h] [-d DIR] [-l]
PROG: error: /home/foo/fr directory not found
如果要保留
type=directory
,则需要查找或编写具有该名称的函数,例如

def directory(astring):
    # do something to validate this string
    # or transform it into something else
    return astring

在本例中,-h只是--help的一个快捷方式,它不会改变问题。因此,我不知道,因为我运行了您的代码,它工作正常,正如您所希望的。但我运行的是python 2.7。也许,您没有创建目录?是的,我没有创建用于测试的目录。问题在于回溯。ThanksTraceback-因为您是手动启动的-“启动ArgumentTypeError”根据
-dir
-loc
选项的顺序,其行为会有所不同。如果
-loc
是第一个,则使用默认的
dir
值,而不是给定值。那么
type=directory
呢?那是干什么的?那是真的。这应该在手册页中解释。我不知道该怎么做。