Skip to main content
 首页 » 编程设计

python之使用自定义 cmd 选项运行 web.py 应用程序

2025年05月04日33jirigala

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

当我尝试将简单的 web.py 教程示例与 optparse 结合使用时,我遇到了一个问题,即 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 

请您参考如下方法:

这有点 hack,但我想你可以这样做:

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()