无法在后台使用线程 运行 python http 服务器
Unable to run python http server in background with threading
我正在尝试 运行 python 在后台使用线程的 http 服务器。我遇到了几个执行以下操作的参考资料:
import threading
import http.server
import socket
from http.server import HTTPServer, SimpleHTTPRequestHandler
debug = True
server = http.server.ThreadingHTTPServer((socket.gethostname(), 6666), SimpleHTTPRequestHandler)
if debug:
print("Starting Server in background")
thread = threading.Thread(target = server.serve_forever)
thread.daemon = True
thread.start()
else:
print("Starting Server")
print('Starting server at http://{}:{}'.format(socket.gethostname(), 6666))
server.serve_forever()
当 thread.daemon 设置为 True 时,程序将在不启动服务器的情况下完成(端口 6666 上没有 运行ning)。
当我将 thread.daemon 设置为 False 时,它会在前台启动服务器并阻止终端,直到我手动将其终止。
知道如何进行这项工作吗?
在这两种情况下,服务器都在后台启动,在单独的线程中。这意味着 thread.start()
启动服务器并且 python 继续执行主线程中的其余代码。
但是,您的程序中似乎没有其他可执行的内容。 Python 到达文件末尾,主线程完成。
OS 要求所有 non-daemon 个线程在进程完成之前完成。当 thread.daemon
设置为 False
时,OS 会等待直到服务器线程退出(这永远不会发生,正如名称 serve_forever
所暗示的那样)。当它是 True
时,进程在主线程完成后立即关闭。
在 thread.start()
之后放置任何你想要异步执行的代码,你就完成了!
我正在尝试 运行 python 在后台使用线程的 http 服务器。我遇到了几个执行以下操作的参考资料:
import threading
import http.server
import socket
from http.server import HTTPServer, SimpleHTTPRequestHandler
debug = True
server = http.server.ThreadingHTTPServer((socket.gethostname(), 6666), SimpleHTTPRequestHandler)
if debug:
print("Starting Server in background")
thread = threading.Thread(target = server.serve_forever)
thread.daemon = True
thread.start()
else:
print("Starting Server")
print('Starting server at http://{}:{}'.format(socket.gethostname(), 6666))
server.serve_forever()
当 thread.daemon 设置为 True 时,程序将在不启动服务器的情况下完成(端口 6666 上没有 运行ning)。 当我将 thread.daemon 设置为 False 时,它会在前台启动服务器并阻止终端,直到我手动将其终止。
知道如何进行这项工作吗?
在这两种情况下,服务器都在后台启动,在单独的线程中。这意味着 thread.start()
启动服务器并且 python 继续执行主线程中的其余代码。
但是,您的程序中似乎没有其他可执行的内容。 Python 到达文件末尾,主线程完成。
OS 要求所有 non-daemon 个线程在进程完成之前完成。当 thread.daemon
设置为 False
时,OS 会等待直到服务器线程退出(这永远不会发生,正如名称 serve_forever
所暗示的那样)。当它是 True
时,进程在主线程完成后立即关闭。
在 thread.start()
之后放置任何你想要异步执行的代码,你就完成了!