1

I am using an API where I can fetch data with. From the data output I am trying to get specific portions so I can place it nicely in a formatted text. I want to fetch the data every 5 seconds, so I get fresh info. I do not want that the data is prompted below the output from the first run, but rather replace the current value(s) for the updated value(s). As I'm pretty bad with python, I hope someone can give me some advice.

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

This works fine. It just keeps posting the output under each other. I wish to have everything static, except the data['amount'], and data['matches'], which should keep updating without actually posting it on newlines. I have tried resolving this by clearning the screen, but that is not the desired solution.

Jonny
  • 19
  • 1

1 Answers1

0

Just add end='\r' to your print statement:

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()
pieca
  • 2,463
  • 1
  • 16
  • 34
  • Thanks, but how do I actually do this with the output from my request? – Jonny Apr 11 '19 at 11:29
  • @Jonny replace `data` variable with the content from your request. You didn't post actual api url so I replaced with dummy dictionary having the same keys for testing. Any dictionary having keys 'amount' and 'matches' will work – pieca Apr 11 '19 at 11:40
  • Thanks, it works. It just doesn't work when I have a multline print: print ("Amount: {} \n Games played: {} \n".format( data['amount'], data['matches']), end='\r') – Jonny Apr 11 '19 at 11:49
  • @Jonny if you need multiline output, try [this](https://stackoverflow.com/a/39016449/5550835) – pieca Apr 11 '19 at 12:02
  • Thanks. I am however trying to avoid such situation. – Jonny Apr 11 '19 at 12:07