I am using the Bottle application framework for Python ( pip install bottle) and want to run a web application that can only be accessed from the local computer (this is essentially a desktop application that uses a browser for the GUI). To start the bottle app, I need to call bottle.run(), but this blocks until the script is executed. You stop it by pressing Ctrl-C.
However, I also want this application to open a web browser for localhost by calling webbrowser.open(). The problem is that I cannot call webbrowser.open()first because the web application will not start, but if I call bottle.run(), it will not return first while the web application is running, and I cannot continue to call webbrowser.open().
My solution was to put a call webbrowser.open()inside a thread:
import bottle
import threading
import webbrowser
import time
class BrowserOpener(threading.Thread):
def run(self):
time.sleep(1)
webbrowser.open('http://localhost:8042')
print('Browser opened')
@bottle.route('/')
def index():
return 'hello world!'
BrowserOpener().start()
bottle.run(host='localhost', port=8042)
The problem with this now is that pressing Ctrl-C in the terminal does not work, so I cannot stop the web application other than closing the terminal. I am not sure why this is so: it 'Browser opened'is printed on the screen, so I know that it is webbrowser.open()returning.
I am on Windows 7.
, webbrowser python self._running = False, . , join() .
os.system('python openbrowser.py') script, -, Ctrl-C.
threading.Timer(1, webbrowser.open, ['http://localhost:8042']).start(), Ctrl-C.
, ?