1
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. 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?

Gert Cuykens
  • 6,845
  • 13
  • 50
  • 84

3 Answers3

6

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)

Vin-G
  • 4,920
  • 2
  • 21
  • 16
1

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.

Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67
1

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 &.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
  • How do you detect a console only in python? Script is intended too run on as much noob machines as possible where they just have too launch this script. – Gert Cuykens Apr 14 '10 at 18:42