httpd = make_server('', 80, server)
webbrowser.open(url)
httpd.serve_forever()
This works cross platform except when I launch it on a putty ssh terminal.开发者_Python百科 How can i trick the console in opening the w3m browser in a separate process so it can continue to launch the server?
Or if it is not possible to skip webbrowser.open when running on a shell without x?
Maybe use threads? Either put the server setup separate from the main thread or the browsweropen instead as in:
import threading
import webbrowser
def start_browser(server_ready_event, url):
print "[Browser Thread] Waiting for server to start"
server_ready_event.wait()
print "[Browser Thread] Opening browser"
webbrowser.open(url)
url = "someurl"
server_ready = threading.Event()
browser_thread = threading.Thread(target=start_browser, args=(server_ready, url))
browser_thread.start()
print "[Main Thread] Starting server"
httpd = make_server('', 80, server)
print "[Main Thread] Server started"
server_ready.set()
httpd.serve_forever()
browser_thread.join()
(putting the server setup in the main thread lets it catch ctrl+c events i think)
According to the Python docs:
Under Unix, graphical browsers are preferred under X11, but text-mode browsers will be used if graphical browsers are not available or an X11 display isn’t available. If text-mode browsers are used, the calling process will block until the user exits the browser.
So you will need to detect if you are in a console-only environment, and take an appropriate action such as NOT opening the browser.
Alternatively, you might be able to define the BROWSER
environment variable - as Alexandre suggests - and have it run a script that either does nothing or opens the browser in the background via &
.
Defining the BROWSER
environment variable in a login script to something like w3m
should fix the problem.
Edit: I realize that you don't want your script to block while the browser is running.
In that case perhaps something simple like:
BROWSER="echo Please visit %s with a web browser"
would work better.
精彩评论