[英]Starting simple python web server in background and continue script execution
I am attempting to start a simple HTTP web server in python and then ping it with the selenium driver.我正在尝试在 python 中启动一个简单的 HTTP Web 服务器,然后使用 selenium 驱动程序 ping 它。 I can get the web server to start but it "hangs" after the server starts even though I have started it in a new thread.
我可以启动 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()
The server starts but the script execution stops after the server has started.服务器启动但脚本执行在服务器启动后停止。 The code after I start the thread is never executed.
我启动线程后的代码永远不会执行。
How do I get the server to start and then have the code continue execution?如何让服务器启动然后让代码继续执行?
Start your thread with function create_server
(without calling it ()
):使用函数
create_server
启动您的线程(不调用它()
):
thread.start_new_thread(create_server, tuple())
If you call create_server()
, it will stop at httpd.serve_forever()
.如果您调用
create_server()
,它将在httpd.serve_forever()
处停止。
For Python 3 you can use this:对于 Python 3,你可以使用这个:
import threading
threading.Thread(target=create_server).start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.