python - 当自定义命名空间为对象时,未设置默认 argparse 参数值

标签 python python-3.x command-line-interface python-3.6

我注意到在使用自定义命名空间对象时没有设置默认参数值:

import argparse

class CliArgs(object):
    foo: str = 'not touched'


parser = argparse.ArgumentParser()
parser.add_argument('--foo', default='bar')

args = CliArgs()
parser.parse_args(namespace=args)
print(args.foo) # 'not touched'

print(parser.parse_args()) # 'bar'

ideone: https://ideone.com/7P7VxI

我希望在这两种情况下都设置 bar

这是预期的吗?我在 the documentation 中看不到它虽然。

如果它是预期的,那么除了使用一些自定义操作之外真的没有办法实现它吗?

UPD:我将其报告为文档错误 https://bugs.python.org/issue38843

最佳答案

是的,这是预期的。 编辑:但仅适用于 argparse 开发人员。

参见argparse.py

def parse_known_args(...):
    # add any action defaults that aren't present
    for action in self._actions:
        if action.dest is not SUPPRESS:
            if not hasattr(namespace, action.dest):
                if action.default is not SUPPRESS:
                    setattr(namespace, action.dest, action.default)
        # add any parser defaults that aren't present
        for dest in self._defaults:
            if not hasattr(namespace, dest):
                setattr(namespace, dest, self._defaults[dest])

add any action defaults that aren't present

在您的示例中,如果您在默认对象中设置属性,效果将是相同的:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo', default='bar')

args = argparse.Namespace()
args.foo = 'not touched'
parser.parse_args(namespace=args)
print(args.foo) # 'not touched'

关于python - 当自定义命名空间为对象时,未设置默认 argparse 参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925420/

相关文章:

php - 从网页运行 PHP CLI 脚本

Python Pandas.Series.asof : Cannot compare type 'Timestamp' with type 'struct_time'

python - 如何将字典值转换为字典集

python - 控制数据库查询流程的更好方法

python - 获取用户名而不仅仅是查看列表中的 ID

python - 安装Python 3.8.1 --with-openssl --without-root/apt/yum

python-3.x - TypeError: 'NoneType'对象在opencv中不可迭代

python - 多次选择并复制一个随机文件

python - 如何将 Python 包 pip 安装到虚拟环境中并在普通 shell 中访问 CLI 命令

JavaScript CLI : how to invoke bin file so that I can run integration tests with Jest