【问题标题】:Running web.py app with custom cmd options使用自定义 cmd 选项运行 web.py 应用程序
【发布时间】:2012-04-03 19:37:28
【问题描述】:

我想使用 web.py 为一些更大的库构建一个 http 接口,它还提供了一个带有可选参数的命令行脚本。

当我尝试结合 optparse 的简单 web.py 教程示例时,我遇到的问题是 web.py 总是将第一个 cmd 参数作为端口,这不是我想要的。有没有办法告诉 web-py 不要检查命令行参数。这是一个例子:

#!/usr/bin/env python
# encoding: utf-8
"""
web_interface.py: A simple Web interface

"""

import optparse
import web

urls = ("/.*", "hello")
app = web.application(urls, globals())

class hello:
    def GET(self):
        return 'Hello, world!\n'

if __name__ == "__main__":
    p = optparse.OptionParser()
    p.add_option('--test', '-t', help="the number of seed resources")
    options, arguments = p.parse_args()
    print options.test
    app.run()

...我想按如下方式运行:

python web_interface.py -t 10

【问题讨论】:

  • 遇到了类似的问题,并通过编辑sys.argv 来解决它,以便在它们到达 web.py 应用程序之前根据this 的答案删除额外的字符串。

标签: python web.py


【解决方案1】:

这有点小技巧,但我想你可以这样做:

import sys
...

if __name__ == "__main__":
    p = optparse.OptionParser()
    p.add_option('--test', '-t', help="the number of seed resources")
    options, arguments = p.parse_args()
    print options.test

    # set sys.argv to the remaining arguments after
    # everything consumed by optparse
    sys.argv = arguments

    app.run()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    相关资源
    最近更新 更多