There are cases that we need to limit the options that a user will provide as command line arguments, to do this the easy way in python we can use the argparse module which provides a nice way to validate / handle options.
在某些情况下,我们需要限制用户将作为命令行参数提供的选项,要在python中轻松实现此目的,我们可以使用argparse模块,该模块提供了一种验证/处理选项的好方法。
More often i needed to limit the choices of a command line option, to do this i used something like the following:
我经常需要限制命令行选项的选择,为此,我使用了以下内容:
parser = argparse.ArgumentParser()parser.add_argument('--ssh-gw',
action = 'store',
type = str,
help = "SSH Gateway.",
required = False,
choices = ["grvgw1","grvgw2","grvgw3","grvgw4"],
default = False)
I created a command line option named ‘ — ssh-gw’ which can accept as valid options any value from grvgw1,grvgw2,grvgw3,grvgw4, is pretty handy but it has a problem, hosts are case in-sensitive, this means that its absolutely logical and valid for a user to enter GRVGW1 instead of grvgw1, which in this case our code will fail and will nag with an error.
我创建了一个名为“-ssh-gw”的命令行选项,该选项可以接受来自grvgw1,grvgw2,grvgw3,grvgw4的任何值作为有效选项,这非常方便,但是存在问题,主机不区分大小写,这意味着对于用户而言,输入GRVGW1而不是grvgw1是绝对合乎逻辑和有效的,在这种情况下,我们的代码将失败并出现错误。
kpatronas@nostromo:~/scripts$ ./ssh_conn.py --ssh-gw GRVGW1
usage: store_explorer.py [-h] [--ssh-gw {grvgw1,grvgw2,grvgw3,grvgw4}]
ssh_conn.py: error: argument --ssh-gw: invalid choice: 'GRVGW1' (choose from 'grvgw1', 'grvgw2', 'grvgw3', 'grvgw4')
You have some options here, which are kind of ugly and / or inefficient
您在这里有一些选择,这些选择很难看和/或效率低下
- Add in choices the same hosts in capital letters, which is ugly and inefficient also because it will not work in case of GRVgw1 as input. 用大写字母添加相同的主机,这很丑陋且效率低下,因为在输入GRVgw1的情况下它将不起作用。
- Force user to use only small / capital letters which is ugly 强制用户仅使用难看的小写/大写字母
这是一个聪明而有效的选择 (And here is the clever and efficient option)
By changing this option:
通过更改此选项:
type = str
To:
至:
type = str.lower
This will force all user input for this option to be converted to lower case, which will cover any kind of input, small letters, capital or even mixed.
这将迫使此选项的所有用户输入都转换为小写,这将涵盖任何类型的输入,小写字母,大写或什至大小写。
It’s a very simple solution, probably dead simple, but this is the spirit of Python “keep it simple and stupid”.
这是一个非常简单的解决方案,可能很简单,但这就是Python的精神“保持简单而愚蠢”。
翻译自: https://medium.com/python-in-plain-english/python-case-in-sensitive-argparse-choices-a380e9169fff