【发布时间】:2018-05-16 17:40:44
【问题描述】:
我正在使用我的解析器
parser.add_argument('owner_type', type=int, required=False, location=location)
我希望能够在该字段owner_type 中同时发送int 和str。
有没有办法做到这一点?
在文档中没有找到任何内容。
【问题讨论】:
我正在使用我的解析器
parser.add_argument('owner_type', type=int, required=False, location=location)
我希望能够在该字段owner_type 中同时发送int 和str。
有没有办法做到这一点?
在文档中没有找到任何内容。
【问题讨论】:
你可以这样做:
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'>
【讨论】:
我不认为这是可能的。但是你想做什么? 你不能传递一个字符串,然后在做一个
try:
owner_type=int(args.owner_type)
#it's a int
except:
owner_type = args.owner_type
#it's a string
【讨论】: