英文:
Stop Prometheus client in python script
问题
需要使用Python代码停止prometheus_client.http_server
。
我有一个外部的Python应用程序需要进行单元测试。它有一个方法使用start_http_server(port)
启动prometheus_client
。我需要使用多个测试来对其进行单元测试(实际上,我不测试prometheus,而是测试其他功能,但无法将prometheus从代码中删除)。由于我需要进行多个测试,因此需要多次启动和停止方法,但在第一次尝试后它会退出,因为Prometheus客户端正在占用端口,无法再次在相同端口上启动(OSError: [Errno 48] Address already in use
)。
问题是:是否有办法使用Python停止prometheus_client.http_server
?在prometheus_client
文档中没有找到任何关于关闭它的信息...
英文:
Need to stop prometheus_client.http_server
with Python code.
I have external Python application that is to be unit-tested. It has method that starts prometheus_client
with start_http_server(port)
. I need to unit-test it with several tests (indeed I don't test prometheus but other functionalities but can't take prometheus out of the code). As I need several tests so I need to start-stop method several times, but it exits after first attempt as Prometheus client is holding port and can't start again on the same port (OSError: [Errno 48] Address already in use
).
The question: is there any way to stop prometheus_client.http_server
with Python? Didn't find anything in prometheus_client
docs about shutting it down...
答案1
得分: 1
嗯,这并非对我问题的确切回答,但无论如何:我决定start_http_server = Mock(return_value=None)
,以便在单元测试中不启动。
英文:
Well, it's not exact answer to my question but anyway: I decided to start_http_server = Mock(return_value=None)
so that it's not starting in unit-tests.
答案2
得分: 0
尝试使用wsgiref.simple_server.make_server
运行Prometheus服务器。然后,你应该能够在服务器实例上调用.server_close()
方法。
from prometheus_client import start_http_server
from wsgiref.simple_server import make_server
# 启动服务器
port = 8000
httpd = make_server('', port, start_http_server)
# 关闭服务器
httpd.server_close()
英文:
Try to run the prometheus server with wsgiref.simple_server.make_server
instead.
Then you should be able to invoke .server_close()
on the server instance.
from prometheus_client import start_http_server
from wsgiref.simple_server import make_server
# Start the server
port = 8000
httpd = make_server('', port, start_http_server)
# Stop the server
httpd.server_close()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论