【问题标题】:How can I run a local server and open urls from the same python program?如何运行本地服务器并从同一个 python 程序打开 url?
【发布时间】:2017-05-07 15:09:29
【问题描述】:

我想启动一个本地服务器,然后用浏览器从同一个 python 程序打开一个链接。

这是我尝试过的(非常幼稚和愚蠢的尝试):

from subprocess import call
import webbrowser

call(["python", "-m", "SimpleHTTPServer"]) #This creates a server at port:8000
webbrowser.open_new_tab("some/url")

但是,程序不会转到第二条语句,因为服务器仍在后台运行。要打开浏览器,我需要退出服务器,这违背了运行服务器的目的。

谁能帮助我提出一个可行的解决方案?

【问题讨论】:

    标签: python server localhost


    【解决方案1】:

    您可以在守护线程中启动您的 Web 服务器(如果只剩下守护线程,则 Python 程序将退出),然后从主线程发出请求。

    唯一的问题是将你的主线程同步到服务器线程,因为 HTTP 服务器需要一些时间来启动并且在此之前不会处理任何请求。我不知道有一个简单而干净的解决方案来做到这一点,但你可以(有点骇人听闻)只是暂停你的主线程几秒钟(可能更短),然后才开始发出请求。另一种选择是从一开始就向网络服务器发送请求,并期望它们在一段时间内失败。

    这是一个小示例脚本,其中包含一个简单的 HTTP 网络服务器,它通过 TCP 在 localhost:8080 上提供来自本地文件系统的内容,以及一个示例请求,从网络服务器的目录中请求一个文件 foo.txt(在这种情况下也是脚本)开始于。

    import sys
    import requests
    import threading
    import time
    
    from BaseHTTPServer import HTTPServer
    from SimpleHTTPServer import SimpleHTTPRequestHandler
    
    # set up the HTTP server and start it in a separate daemon thread
    httpd = HTTPServer(('localhost', 8080), SimpleHTTPRequestHandler)
    thread = threading.Thread(target=httpd.serve_forever)
    thread.daemon = True
    
    # if startup time is too long we might want to be able to quit the program
    try:
        thread.start()
    except KeyboardInterrupt:
        httpd.shutdown()
        sys.exit(0)
    
    # wait until the webserver finished starting up (maybe wait longer or shorter...)
    time.sleep(5)
    
    # start sending requests
    r = requests.get('http://localhost:8080/foo.txt')
    
    print r.status_code
    # => 200 (hopefully...)
    

    【讨论】:

    • 我自己在看线程。这非常有效。但是,在尝试使用sys.exit(0) 退出时,我收到很多错误(程序最终会结束)说error: [Errno 10054] An existing connection was forcibly closed by the remote host。这是“结束”线程的正确方法还是有更好的方法?
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2015-04-26
    相关资源
    最近更新 更多