gpt4 book ai didi

python - 在后台启动简单的 python Web 服务器并继续执行脚本

转载 作者:行者123 更新时间:2023-12-04 15:55:57 24 4
gpt4 key购买 nike

我正在尝试在 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()

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

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

最佳答案

使用函数 create_server 启动您的线程(不调用它 ()):

thread.start_new_thread(create_server, tuple())

如果您调用 create_server(),它将在 httpd.serve_forever() 处停止。

关于python - 在后台启动简单的 python Web 服务器并继续执行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51659239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com