【问题标题】:Parsing command line options in Jython 2.1在 Jython 2.1 中解析命令行选项
【发布时间】:2012-01-06 04:31:42
【问题描述】:

我正在将 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 中还有哪些其他选择?

【问题讨论】:

    标签: python websphere jython websphere-6.1 wsadmin


    【解决方案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 存在。

    【讨论】:

      【解决方案2】:

      请注意,大多数库实际上都是简单的 Python 模块,您可以在 Python 发行版中的 \Lib 下找到它们,因此通常一个简单的文件副本会为您提供库。

      在这种情况下,我将 optparse.py(及其依赖项 textparse.py)从 Python 2.7 复制到 Jython 2.2,它似乎可以正常导入。

      【讨论】:

      • 谢谢,这是可能的,但我不打算将不受支持的依赖项添加到生产服务器,尤其是 WebSphere :)
      【解决方案3】:

      这样的事情怎么样:

      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:]
      

      免责声明:未经任何测试。

      【讨论】:

      • 谢谢,刚刚修复了一个小错误 sys.args 应该是 sys.argv。我一直在寻找一个 api,但这个简单的(回想起来很明显!)解决方案有效,足以满足我的需求。
      猜你喜欢
      • 2015-02-28
      • 2017-08-31
      • 2011-03-20
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      • 2015-01-22
      相关资源
      最近更新 更多