【问题标题】:parser.add_argument support multiple types [duplicate]parser.add_argument 支持多种类型
【发布时间】:2018-05-16 17:40:44
【问题描述】:

我正在使用我的解析器

 parser.add_argument('owner_type', type=int, required=False, location=location)

我希望能够在该字段owner_type 中同时发送intstr。 有没有办法做到这一点?

在文档中没有找到任何内容。

【问题讨论】:

    标签: python parsing


    【解决方案1】:

    你可以这样做:

    import argparse
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser(description='Demo.')
        parser.add_argument('-e', dest='owner_type', help="help text")
        args = parser.parse_args()
        owner_type = args.owner_type
    
        if owner_type is not None and owner_type.isdigit():
            owner_type = int(owner_type)
    
        print(type(owner_type))
    

    这仅适用于 int 和字符串。如果您需要处理浮点数,那么您也需要以不同的方式处理这种情况。

    输出:

    ~/Desktop$ python test.py -e 1
    <type 'int'>
    ~/Desktop$ python test.py -e test
    <type 'str'>
    ~/Desktop$ python test.py 
    <type 'NoneType'>
    

    【讨论】:

      【解决方案2】:

      我不认为这是可能的。但是你想做什么? 你不能传递一个字符串,然后在做一个

      try:
       owner_type=int(args.owner_type)
       #it's a int
      except:
       owner_type = args.owner_type
       #it's a string
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-07
        • 2018-07-27
        • 2018-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多