如何检查 Python 中传递的 CLI 参数类型 / 单击

How to check the passed CLI argument type in Python / Click

我正在编写一个接受 intstr 类型参数的点击命令,并且我需要找出函数中传递的参数类型,如本例所示:

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'>

我正在寻找一种方法来执行此命令return:

$ python script.py text
<type 'str'>
$ python script.py 123
<type 'int'>

click 或什至使用 sys.argv 的位置参数将始终为 str 类型,因为 这是您传递给命令行的内容,一个 string.

您需要做的是解析输入并将其转换为字符串或调整您的代码如下所示:

import click

@click.command()
@click.argument('num')
def command(num):
    if num.isnumeric():
        click.echo("integer")
    else:  # Will always be a str no need to check for type.
        click.echo("string")

if __name__ == '__main__':
    command()

这使用 isnumeric() 来检查传递的 str 是否为数字,例如你“123”

"The method isnumeric() checks whether the string consists of only numeric characters. This method is present only on unicode objects."

你也可以这样做:

import click

@click.command()
@click.argument('num')
def command(num):
    if num.isnumeric():
        num = int(num)
    if isinstance(num, int):
        click.echo("integer")
    else:       
        click.echo("string")

if __name__ == '__main__':
    command()

然而,这完全是多余的,除非您打算稍后使用 num 并且您需要它是 int 类型。

最后你应该使用 isinstance(num, int) 而不是 type()

更多信息在这里:Differences between isinstance() and type() in python

它通常被认为比 ask for forgiveness not permission 更 Pythonic。

try:
    int(num)
    click.echo("integer")
except ValueError:
    click.echo("string")

这将通过尝试在 try 块中转换为 int 来实现。如果字符串可以转换为int,那么它一定是int,否则就是字符串