N3VO
N3VO

Reputation: 39

Key error after running python json for set amount of time

I have this script below that takes crypto data (price) and sends it to a small led sign, the problem is the script will run for a bit but then I get the key error: 'price' which stops the script, weird thing is 'price' works for awhile every time. I am using a cron job to run the script every minute for now but I feel like there is a simpler way of doing this. Is there a way to run/reset the script again if it I get an error? This is on a raspberry pi so there is no physical way for me to restart it without plugging it back into the TV, which I don't want obviously. Many thanks for the help!

#!/usr/bin/python
import time, json, requests
from pyledsign.minisign import MiniSign



def btc():
    btcTick= requests.get('https://api.gdax.com/products/BTC-
    usd/ticker') # replace buy with spot_rate, sell etc
    return btcTick.json()['price'] # replace amount with currency etc

def ltc():
    ltcTick= requests.get('https://api.gdax.com/products/LTC-
    usd/ticker') # replace buy with spot_rate, sell etc
    return ltcTick.json()['price']


while True:
    btcUSD = float(btc())
    ltcUSD = float(ltc())

    print btcUSD
    print ltcUSD

mysign = MiniSign(devicetype='sign')

mysign.queuemsg(data='B: ' + '$' + str(btcUSD) +  ' L: ' + '$' + 
str(ltcUSD) , effect="snow", speed=5)
mysign.sendqueue(device='/dev/ttyUSB0', packetdelay=5.0);

time.sleep(60)

Upvotes: 0

Views: 208

Answers (1)

MCBama
MCBama

Reputation: 1490

Most likely one of your requests is sending back some different looking data (or possibly timing out) so just do a check before attempting to return the price.

import time
while True:
    try:
        btcUSD = float(btc())
        ltcUSD = float(ltc())

        print btcUSD
        print ltcUSD
        time.sleep(1)
    except KeyError as e:
      print('Key not found')

If you want to have a more fancy way of handling it, I would suggest figuring out exactly what you are getting back from your request and going from there because clearly you're not getting the same message back every time. Wrapping in a try/except is simply good practice though so I would do that regardless of what you find out about the response you're getting.

The try/except will keep your script from dying as well so you won't have to restart it.

Bolded for Emphasis: I would also suggest you put a sleep inside your while loop. Spamming a website with a bunch of requests will often get the website to block you since you've basically written a DoS attack.

Upvotes: 1

Related Questions