我想在线程中或作为并行进程运行Web服务器本地化,然后能够在同一个python程序中从该Web服务器查询URL。 我正在构建 html 自我激励幻灯片,然后使用 qt 在网络浏览器中显示它们。
Web 服务器将仅在本地以非常低的数量进行查询。
我尝试使用线程来做到这一点,现在这个程序使用多处理。我从两者中都获得了类似的堆栈跟踪。
我的问题:如何让 Web 服务器运行,同时又不阻止 Web 服务器启动后执行的代码?
import http.server
import socketserver
import os
from multiprocessing import Process
import time
def run_webserver():
cwd = os.getcwd()
os.chdir("./www/public")
PORT = 8002
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
return httpd
if __name__ == '__main__':
httpd = run_webserver()
p = Process(target=httpd.serve_forever, args=())
p.start()
p.join()
# do other work
for i in range(200):
print(str(i))
time.sleep(500)
serving at port 8002
Process Process-1:
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/ process.py", line 249, in _bootstrap
self.run()
File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/ process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 233, in serve_forever
selector.register(self, selectors.EVENT_READ)
File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 351, in register
key = super().register(fileobj, events, data)
File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 237, in register
key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)
File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 224, in _fileobj_lookup
return _fileobj_to_fd(fileobj)
File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 41, in _fileobj_to_fd
raise ValueError("Invalid file descriptor: {}".format(fd))
ValueError: Invalid file descriptor: -1
好的,让它工作了。
import http.server
import socketserver
import os
import multiprocessing
import time
def run_webserver():
os.chdir("./www/public")
PORT = 8002
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(('0.0.0.0', PORT), Handler)
#the following throws an exception
#with socketserver.TCPServer(("0.0.0.0", PORT), Handler) as httpd:
# print("serving at port", PORT)
httpd.serve_forever(poll_interval=0.5)
return
if __name__ == '__main__':
p = multiprocessing.Process(target=run_webserver, args=())
p.daemon = True
p.start()
# do other work
for i in range(200):
print(str(i))
time.sleep(1)