停止Python脚本中的Prometheus客户端。

huangapple go评论53阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2023年5月11日 03:31:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定