【问题标题】:Starting simple python web server in background and continue script execution在后台启动简单的 python web 服务器并继续执行脚本
【发布时间】:2019-01-10 13:22:07
【问题描述】:

我正在尝试在 python 中启动一个简单的 HTTP Web 服务器,然后使用 selenium 驱动程序 ping 它。我可以启动 Web 服务器,但它在服务器启动后“挂起”,即使我已在新线程中启动它。

from socket import *
from selenium import webdriver
import SimpleHTTPServer
import SocketServer
import thread


def create_server():
    port = 8000
    handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", port), handler)
    print("serving at port:" + str(port))
    httpd.serve_forever()


thread.start_new_thread(create_server())

print("Server has started. Continuing..")

browser = webdriver.Firefox()
browser.get("http://localhost:8000")

assert "<title>" in browser.page_source
thread.exit()

服务器启动,但脚本执行在服务器启动后停止。我启动线程后的代码永远不会执行。

如何让服务器启动,然后让代码继续执行?

【问题讨论】:

  • 你在start_new_thread 之前执行create_server() - 这将执行serve_forever() 并且你被卡住了。比如把它放在lambda里面。
  • 如果线程永远不会完成它的任务,它不应该超出它开始的那一行。
  • 您应该使用thread.start_new_thread(create_server)(注意缺少的括号),否则您将调用函数本身而不是让线程代码为您执行此操作。更好的是,使用 threading 模块为线程提供更舒适的高级接口。

标签: python simplehttpserver


【解决方案1】:

用函数create_server 开始你的线程(不调用它()):

thread.start_new_thread(create_server, tuple())

如果您拨打create_server(),它将停在httpd.serve_forever()

【讨论】:

    【解决方案2】:

    对于 Python 3,你可以使用这个:

    import threading
    
    threading.Thread(target=create_server).start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 2017-06-14
      • 2020-03-21
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多