【发布时间】:2014-01-21 01:20:55
【问题描述】:
我必须解析参数,所以我使用了argparse 模块。这适用于 Python 3.3 和 Python 2.7。但有时我不得不将它与 Jython 一起使用,而 Jython 的最后一个稳定版本是 2.5.3。这个版本没有argparse 模块所以我使用了旧的optparse 模块:
args = None
try:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--url", action="store", dest="url", default=url, help='test script URL like "http://127.0.0.1/isof/hdb_ver_xml.hdb" or "hdb://127.0.0.1/isof/hdb_ver_xml.hdb"')
parser.add_argument("-t", "--threads", action="store", type=int, dest="threads_cnt", default=threads_cnt, help='threads count')
parser.add_argument("-T", "--timeout", action="store", type=int, dest="timeout_minutes", default=timeout_minutes, help='timeout in minutes')
args = parser.parse_args()
except:
import optparse
parser = optparse.OptionParser()
parser.add_option("-u", "--url", action="store", dest="url", default=url, help='test script URL like "http://127.0.0.1/isof/hdb_ver_xml.hdb" or "hdb://127.0.0.1/isof/hdb_ver_xml.hdb"')
parser.add_option("-t", "--threads", action="store", type=int, dest="threads_cnt", default=threads_cnt, help='threads count')
parser.add_option("-T", "--timeout", action="store", type=int, dest="timeout_minutes", default=timeout_minutes, help='timeout in minutes')
args, _ = parser.parse_args()
return args
对我来说,这段代码看起来很难看,因为任何更改都必须在 2 个地方进行。当然我可以使用类似的东西:
OPT_THREADS_HELP = 'threads count'
...
... help=OPT_THREADS_HELP
这会有所帮助,但也许有更好的方法来编写这样的代码。有什么想法吗?
【问题讨论】:
-
我担心你最好的选择是使用
optparseonly;它在 Python 3.3 和 3.4 中仍然可用。
标签: python coding-style jython argparse optparse