我必须解析参数,所以我使用了argparse
模块。这在python3.3和python2.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
对我来说,这段代码看起来很难看,因为任何更改都必须在两个地方进行。当然,我可以用类似的方法:
^{pr2}$这会有一点帮助,但也许有更好的方法来编写这样的代码。有什么想法吗?在
你考虑过把你的论点分开存放吗?在
然后,无论使用哪个库,都可以调用:
^{pr2}$您可以进一步简化,允许您通过单独使用绑定方法来减少
^{3}$try
块中的代码:最好的选择是只使用一个命令行参数解析库。在
optparse
在python3.3和3.4中仍然可用,并且还没有宣布何时删除它(如果有的话)。是的,它已被弃用,不会收到新版本,但它仍然可以正常工作。在当您需要支持如此广泛的Python版本时,不要试图重复工作。如果您的需求是由
optparse
来满足的,那么使用就可以了。在如果您不介意使用第三方库,我建议您尝试docopt:
你在那里做事的方式:
见docopt
Docopt is also successfully used with Jython!在
相关问题 更多 >
编程相关推荐