python-3.x - 如何拒绝负数作为 Argparse 模块中的参数

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

我有一个时间参数,它可以是除负数和零以外的任何数字

parser.add_argument("-t", "--time",
                    default=2, type=int,
                    help="Settings up the resolution time")

如何正确使用选择选项?

最佳答案

您可以将任何转换函数作为 type= add_argument 的参数.使用您自己的转换功能,其中包括额外的检查。

def non_negative_int(x):
    i = int(x)
    if i < 0:
        raise ValueError('Negative values are not allowed')
    return i

parser.add_argument("-t", "--time",
                    default=2, type=non_negative_int,
                    help="Settings up the resolution time")

关于python-3.x - 如何拒绝负数作为 Argparse 模块中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43299736/

相关文章:

python-3.x - 使用文件夹结构迭代 S3 存储桶中的文件

command-line-interface - 用于重新加载部署的 WildFly CLI 命令

python - 更改 argparse 使用消息参数顺序

python - 像典型的过滤程序一样解析 cmd args

python-3.x - LSTM 的预期隐藏状态维度没有考虑批量大小

macos - 使用Python 3在scikit-learn上进行大数据序列化

python - 为什么我在这里需要 shell=True 才能让 Python 的 subprocess.check_output 工作?

android - 使用 phonegap 运行 android 命令时创建 android 子项目时出错

python - 如何在 Python 3 Click 应用程序中遍历 shell 提供的文件列表?

python - 打包和argparse