Python 参数提供不太相似的限制功能

发布于 2024-12-16 01:05:26 字数 343 浏览 2 评论 0原文

知道是否有一种干净的方法来使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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野生奥特曼 2024-12-23 01:05:26

在 argparse 中,您可以定义一个可选的位置整数参数。负值对于用户来说就像是提供了一个选项:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('limit', type=int, nargs='?')
args = parser.parse_args()
if args.limit is not None:
    print "Limiting to %d." % -args.limit

在这种情况下,默认的帮助文本并不合理,但可以使用 add_argumentmetavar 关键字参数进行调整,使用例如“-n”

我只能想出一个看起来很糟糕的方法来使用 optparse 来做到这一点。基本上为数字可以开头的每个数字定义一个单独的选项:

from optparse import OptionParser
parser = OptionParser()
parser.add_option("-1")
parser.add_option("-2")
options,args = parser.parse_args()
if options.__dict__["1"] is not None:
    print "Your number was %d." % (int("1"+options.__dict__["1"]))
elif options.__dict__["2"] is not None:
    print "Your number was %d." % (int("2"+options.__dict__["2"]))

对于 9 以内的所有数字,依此类推。还要考虑是否需要考虑 0...

In argparse, you can define an optional positional integer argument. Negative values will then look to the user like giving an option:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('limit', type=int, nargs='?')
args = parser.parse_args()
if args.limit is not None:
    print "Limiting to %d." % -args.limit

The default help text is not reasonable in this case, but can be adjusted with the metavar keyword argument to add_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:

from optparse import OptionParser
parser = OptionParser()
parser.add_option("-1")
parser.add_option("-2")
options,args = parser.parse_args()
if options.__dict__["1"] is not None:
    print "Your number was %d." % (int("1"+options.__dict__["1"]))
elif options.__dict__["2"] is not None:
    print "Your number was %d." % (int("2"+options.__dict__["2"]))

and so on for all digits up to 9. Also think about whether 0 needs to be considered...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文