Python 参数提供不太相似的限制功能
知道是否有一种干净的方法来使optparse
绕过/处理通用-XXX
选项?
我的案例是一个应用程序,我想为其提供一个类似于 less
的选项,以将应用程序的输出条目限制为 -
之后定义的数量,
例如
myapp.py list -10
我想我可以覆盖 sys.argv
dict 以避免 optparse 引发错误并手动解析/删除自定义参数,但我想知道 optparse lib 是否预见到并提供了更好的情况方法来做到这一点。
Any idea if there is a clean way to make optparse
bypass/handle a generic -XXX
option ?
My case is an application for which i want to provide a less
like option to limit the application s output entries to the number defined after -
e.g.
myapp.py list -10
i guess i could overwrite sys.argv
dict to avoid optparse
from raising an error and manually parse/remove the custom argument, but i'm wondering if this is a case that optparse lib foresees and provides a better way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 argparse 中,您可以定义一个可选的位置整数参数。负值对于用户来说就像是提供了一个选项:
在这种情况下,默认的帮助文本并不合理,但可以使用
add_argument
的metavar
关键字参数进行调整,使用例如“-n”
。我只能想出一个看起来很糟糕的方法来使用 optparse 来做到这一点。基本上为数字可以开头的每个数字定义一个单独的选项:
对于 9 以内的所有数字,依此类推。还要考虑是否需要考虑 0...
In argparse, you can define an optional positional integer argument. Negative values will then look to the user like giving an option:
The default help text is not reasonable in this case, but can be adjusted with the
metavar
keyword argument toadd_argument
, using e.g."-n"
.I can only come up with a nasty looking way to do this with optparse. Basically define an individual option for each digit that the number can start with:
and so on for all digits up to 9. Also think about whether 0 needs to be considered...