我正在将 Jython 2.1 用于 wsadmin 脚本,并希望找到一种更好的方法来解析命令行选项。我目前正在这样做:
-> deploy.py foo bar baz
然后在脚本中:
foo = sys.arg[0]
bar = sys.arg[1]
baz = sys.arg[2]
但想这样做:
-> deploy.py -f foo -b bar -z baz
optparse在 2.3 中被添加到 python 中。在 Jython 2.1 中我还有哪些其他选择?
像这样的东西怎么样:
args = sys.argv[:] # Copy so don't destroy original
while len(args) > 0:
current_arg = args[0]
if current_arg == '-f':
foo = args[1]
args = args[2:]
elif current_arg == '-b':
bar = args[1]
args = args[2:]
elif current_arg == '-z':
baz = args[1]
args = args[2:]
else:
print 'Unknown argument: %r' % args[0]
args = args[1:]
免责声明:未经任何测试。
getopt 库与 Jython 2.1 捆绑在一起。它不像新的参数解析模块那么花哨,但仍然比滚动你自己的参数解析要好得多。
import getopt
getopt 的文档:http: //docs.python.org/release/2.1.1/lib/module-getopt.html
我在 WebSphere Appserver 7.0.0.x 下使用它。我看到您已经用 websphere-6.1 标记了这个问题 - 不幸的是,我现在手头没有 WAS 6.1 系统可供测试。
编辑:在 WebSphere 6.1 上验证;getopt 存在。
请注意,大多数库实际上是简单的 Python 模块,您可以在 Python 发行版的 \Lib 下找到它们,因此通常一个简单的文件副本将为您提供库。
在这种情况下,我将 optparse.py(及其依赖项 textparse.py)从 Python 2.7 复制到 Jython 2.2,它似乎可以正常导入。