简体   繁体   English

python webbrowser.open(网址)

[英]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. 这可以跨平台工作,除非我在腻子ssh终端上启动它。 How can i trick the console in opening the w3m browser in a separate process so it can continue to launch the server? 我如何在一个单独的过程中打开w3m浏览器来欺骗控制台,以便它可以继续启动服务器?

Or if it is not possible to skip webbrowser.open when running on a shell without x? 还是在没有x的shell上运行时无法跳过webbrowser.open?

Maybe use threads? 也许使用线程? Either put the server setup separate from the main thread or the browsweropen instead as in: 将服务器设置与主线程或browsweropen分开放置,如下所示:

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) (将服务器设置放在主线程中可以使其捕获我认为的ctrl + c事件)

Defining the BROWSER environment variable in a login script to something like w3m should fix the problem. 在登录脚本中将BROWSER环境变量定义为w3m应该可以解决此问题。

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. BROWSER="echo Please visit %s with a web browser"会更好。

According to the Python docs : 根据Python文档

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. 在Unix下,图形浏览器在X11下是首选,但如果图形浏览器不可用或X11显示器不可用,则将使用文本模式浏览器。 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 & . 另外,您可能能够定义BROWSER环境变量(如Alexandre建议的那样),并让它运行一个脚本,该脚本要么不执行任何操作,要么通过&在后台打开浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM