使用计时器和字符串表示的Python请求

2024-05-16 19:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个API,在那里我可以用它来获取数据。从数据输出中,我试图得到特定的部分,这样我就可以很好地将其放入格式化文本中。 我想每5秒钟取一次数据,这样我就能得到新的信息。我不希望在第一次运行的输出下面提示数据,而是将当前值替换为更新后的值。 由于我对python很不在行,我希望有人能给我一些建议。你知道吗

import requests
import threading

def dostuff()
      threading.Timer(5.0, dostuff).start()
      r = requests.get('https://api')
      data = r.json()
      print("Amount:", data['amount'])
      print("Games played:", data['matches'])

dostuff()

这个很好用。它只是不断地在彼此下面发布输出。 我希望所有东西都是静态的,除了数据['amount']和数据['matches'],它们应该不断更新,而不实际地在新行上发布。我试图通过清除屏幕来解决这个问题,但这不是理想的解决方案。你知道吗


Tags: 数据文本importapi信息datadefrequests
1条回答
网友
1楼 · 发布于 2024-05-16 19:24:52

只需在print语句中添加end='\r'

import requests
import threading
import random

def dostuff():
      threading.Timer(1.0, dostuff).start()
      # replaced as actual api not posted
      data = {
        'amount': round(random.random(), 2),
        "matches": round(random.random(), 2)
      }
      print("Amount: {} Games played: {}".format(
        data['amount'], 
        data['matches']
      ), end='\r')

dostuff()

相关问题 更多 >