如何在等待 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


慕田峪4524236
浏览 310回答 2
2回答

森栏

python中有一个集成库可以做到这一点。查看 tqdm演示。https://github.com/tqdm/tqdm它非常有用,不需要您从头开始构建。如果您确实想从头开始构建某些东西,我相信您需要使用线程,正如之前的答案所述。

呼如林

您需要线程,一个用于主后台进程,一个用于显示进程:import sysimport timeimport threadingimport itertoolsdone = Falseresponse = Nonedef animate():            i = 0    while response is None:      sys.stdout.write('\r')      sys.stdout.write("Fetching MO attribute [%-20s] %d%%" % ('=' * i, 5 * i))      sys.stdout.flush()      time.sleep(0.25)      i += 1t = threading.Thread(target=animate)t.start()# background processresponse = my_api.execute("get some data")done = True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python