python webbrowser方法详解_python webbrowser.open(url)

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?

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.

来源:https://stackoverflow.com/questions/2634235/python-webbrowser-openurl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值