python - 将 argparse 与 Setuptools entry_points 一起使用

标签 python python-2.7 setuptools argparse

我正在编写一个我想使用 Setuptools 分发的脚本。我已将此脚本添加到我的 setup.py 中的 entry_points 部分。

来自 setuptools 文档:

The functions you specify are called with no arguments, and their return value is passed to sys.exit(), so you can return an errorlevel or message to print to stderr.

由于该方法将返回而不是退出,因此它变得更易于测试。出于可测试性目的,我接受默认为 sys.argv 的方法中的参数。到目前为止一切顺利。

当 argparse 添加到混合中时,问题就出现了。当 argparse 无法解析 args 时,它会调用 sys.exit。现在我真的更希望 argparse 不这样做,因为这是由 setuptools 包装器处理的。我想到的第一件事就是覆盖 argparse.ArgumentParser 但后来我看到了这个:

# ===============
# Exiting methods
# ===============
def exit(self, status=0, message=None):
    if message:
        self._print_message(message, _sys.stderr)
    _sys.exit(status)

def error(self, message):
    """error(message: string)

    Prints a usage message incorporating the message to stderr and
    exits.

    If you override this in a subclass, it should not return -- it
    should either exit or raise an exception.
    """
    self.print_usage(_sys.stderr)
    self.exit(2, _('%s: error: %s\n') % (self.prog, message))

所以文档字符串声明我不应该返回并坚持引发异常。我该如何解决?

主要方法,如果我解释得不够透彻的话:

def main(args=sys.argv):
    parser = ArgumentParser(prog='spam')

    # parser is configured here

    parsed = parser.parse_args(args)

    # Parsed args are used here

最佳答案

您不想从error return 的原因是解析器将继续解析。有些错误会在接近尾声时出现(例如关于未解析的字符串),但其他错误可能会提前出现(例如第一个参数字符串的类型错误)。如果您从错误方法返回,parse_args 的行为是不可预测的。通常您希望解析器退出并返回控制您的代码。

您要做的是将 parse_args() 调用包装在 try: except SystemExit: block 中。我经常使用这样的测试脚本:

for test in ['-o FILE',
    ...
         ]:
    print(test)
    try:
        print(parser.parse_args(test.split()))
    except SystemExit:
        pass

您可以使用error 和/或exit 来返回其他类型的异常。他们还可以绕过使用信息。但是无论怎样,您都需要在包装器中捕获异常。

关于python - 将 argparse 与 Setuptools entry_points 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22196711/

相关文章:

Python日期时间到纪元

python - 为什么我的python脚本有两种类型的结果?

python - 如何将命令 Hook 添加到 setuptools 设置中?

python - ImportError : No module named geoip2. 数据库

python - Unicode 字符名称的官方存储库

python - 使用 ctypes 从 python 调用 darknet API(图像作为参数)

python - 为什么在Python的交互式解释器中有时会输出转义字符?

python - 求 python 矩阵中某一列的总和?

python - 使用虚拟 python 和 setuptool 安装 "Easy Install"

python - 我如何说服 setuptools 为来自 setup_require 或 tests_require 的 require 包使用一个临时目录?