我正在编写一个接受int
和str
类型参数的单击命令,我需要找出函数中传递的参数类型,如本例中所示:如何在Python中检查传入的CLI参数类型
import click
@click.command()
@click.argument('num')
def command(num):
if type(num) is int:
click.echo("integer")
elif type(num) is str:
click.echo("string")
if __name__ == '__main__':
command()
本示例不起作用,因为参数类型始终为unicode。
$ python script.py text
<type 'unicode'>
$ python script.py 123
<type 'unicode'>
我正在寻找一种方法,使执行这个命令返回此:
$ python script.py text
<type 'str'>
$ python script.py 123
<type 'int'>
我认为第一个例子很好地完成了这个工作,将使用num作为整数来执行投射 – MMSs
更新了我的答案。使用isinstance()而不是type()。 – alexisdevarennes