Running web.py app with custom cmd options

Go To StackoverFlow.com

2

I would like to use web.py to build an http interface for some larger library, which also provides a command line script that takes optional parameters.

When I tried the simple web.py tutorial example in combination with optparse, I have the problem that web.py always takes the first cmd argument as port, which is not what I want. Is there a way to tell web-py not to check the command line args. Here is an example:

#!/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()

...which I want to run as follows:

python web_interface.py -t 10
2012-04-03 19:37
by behas
Was having a similar problem and solved it by editing sys.argv to remove extra strings before they hit the web.py app as per this answer - cardamom 2018-03-14 13:15


1

It's a bit of a hack, but I guess you could do:

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()
2012-04-03 20:04
by dcrosta
Ads