有没有办法添加一个只能用作 -p
的参数?或 -p=value
,但不是 -p value
我想添加一个可选参数 --parallel/-p
到脚本。这是我希望用户传递它的方式:
./script arg1 arg2 -p # this defaults to 10
./script arg1 arg2 -p=13 # This is fine and will set the value to 13
./script arg1 arg2 -p 13 # This is NOT fine and I want to ban this. Next line will tell why.
./script -p arg1 arg2 # I want -p to be usable regardless of its position.
# But here arg1 will be considered as an argument of -p option, which is unwanted.
最佳答案
不幸的是,您在这里有两个问题:
argparse
只允许 --option=value
对于长参数,当名称长于一个字符时生成。argparse
没办法强制执行--option=value
语法和 --option value
将永远是可能的。您可能必须使用
sys.args
中的内容编写自己的解析器(如果您只有一个选项,可以通过搜索以 "-p"
开头的参数来快速完成。
关于python - Argparse: "-p"或 "-p=value"但不是 "-p value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68095696/