简体   繁体   English

python条件类型转换

[英]python conditional type casting

I'm trying to make sure user arguments are of a certain type, when run script run from cmd line with -> python Script.py argv1 argv2 argv3 etc... 我正在尝试确保使用-> python Script从cmd行运行脚本时,用户参数属于某种类型.py argv1 argv2 argv3等...

The idea is that if the user only enters say 2 cmd line arguments, the rest of the variables in arg_list will default. 这样的想法是,如果用户仅输入2 cmd行参数,则arg_list中的其余变量将为默认值。 I want to make sure that the ones they did enter were of the right type. 我想确保他们输入的是正确的类型。

Below is a mock up of the situation I have. 下面是我的情况的模拟。 At the moment when the if condition fails it's not picked up by the except block (is there a way around this??) In reality there's a lot more variables so putting a try-except for each if clause isn't practical. 当if条件失败时,它不会被except块接受(有没有解决的办法?)。实际上,还有很多变量,因此为每个if子句添加一个try-except是不切实际的。

arg1 = 3.14
arg2 = "Default 1"
arg3 = "Default 2"
arg4 = True
arg_list = [arg1, arg2, arg3, arg4]

for i in range(1, len(sys.argv)):

    try:
        if i==1:
            arg_list[i-1] = float(sys.argv[i])
        elif i==2 or i==3:
            arg_list[i-1] = str(sys.argv[i])
        else i==4:
            arg_list[i-1] = bool(sys.argv[i])

    except TypeError as e:
        # do stuff

Any help would be great, thanks! 任何帮助将是巨大的,谢谢!

typelist = [float, str, str, bool]

for i, item in enumerate(sys.argv[1:]):
    assert type(item) == typelist[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM