带有计时器和字符串替换的Python请求[重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我正在使用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'],它应该保持更新而不实际在新行上发布。我已经尝试通过清除屏幕来解决这个问题,但这不是理想的解决方案。

python json python-requests
1个回答
0
投票

只需将end='\r'添加到您的print语句中:

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()
© www.soinside.com 2019 - 2024. All rights reserved.