首页 > 解决方案 > 如何在等待 API 返回值时等待并显示进度信息

问题描述

我有下面的代码,我正在等待方法调用返回响应。此响应可能需要 10 到 15 秒以上。

我需要在用户等待方法返回响应时显示进度消息。我的 while 条件似乎没有显示进度条。

response = my_api.execute("get some data")
# There is a 10-15 minute delay here...
i = 0
while response is None:
  sys.stdout.write('\r')
  sys.stdout.write("Fetching MO attribute [%-20s] %d%%" % ('=' * i, 5 * i))
  sys.stdout.flush()
  sleep(0.25)
  i += 1

if response.get_output() != "1 instance(s)":
        raise MyError('Could not fetch data. )

for line in response.get_output():
        # Do the actual processing

标签: python

解决方案


python中有一个集成库可以做到这一点。

查看 tqdm演示

https://github.com/tqdm/tqdm

它非常有用,不需要您从头开始构建。

如果您确实想从头开始构建一些东西,我相信您需要使用线程,正如前面的答案所述。


推荐阅读