-1

我编写了这段代码,它通过其 API 从 CoinMarketCap 获取比特币的价格。
然后它在终端打印价格并将其发送到 Arduino,这样我就可以在 LCD 显示器上实时看到它(感谢 Firmata 库)
它工作正常,但问题是价格没有变化,它总是打印相同的价格当我开始代码。

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import time
from pyfirmata import Arduino, util, STRING_DATA


port = 'COM3'

board = Arduino(port)


url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
  'start':'1',
  'limit':'1',
  'convert':'USD'
}
headers = {
  'Accepts': 'application/json',
  'X-CMC_PRO_API_KEY': '646f5705-1a58-48f4-af8a-7156f90d6885',
}

session = Session()
session.headers.update(headers)

try:
  response = session.get(url, params=parameters)
  data = json.loads(response.text)


  for entry in data["data"]:
      symbol = entry["symbol"]
      price1 = str(entry["quote"]["USD"]["price"])[:5]

  while(True):    
    print(symbol + ':', price1)
    board.send_sysex(STRING_DATA, util.str_to_two_byte_iter(symbol))
    board.send_sysex(STRING_DATA, util.str_to_two_byte_iter(price1))
    time.sleep(30)
except (ConnectionError, Timeout, TooManyRedirects) as e:
  print(e)

所以,假设我运行了这个程序,那一刻比特币的价格是 47000 美元。

输出是这样的:

BTC: 47000
BTC: 47000
BTC: 47000
BTC: 47000
BTC: 47000
4

1 回答 1

1

你应该移动这部分:

  response = session.get(url, params=parameters)
  data = json.loads(response.text)


  for entry in data["data"]:
      symbol = entry["symbol"]
      price1 = str(entry["quote"]["USD"]["price"])[:5]

进入您的 while 循环,现在您只需从 API 获取一次数据,然后永远打印/发送它。

然后它看起来像这样:

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import time
from pyfirmata import Arduino, util, STRING_DATA


port = 'COM3'

board = Arduino(port)


url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
  'start':'1',
  'limit':'1',
  'convert':'USD'
}
headers = {
  'Accepts': 'application/json',
  'X-CMC_PRO_API_KEY': '646f5705-1a58-48f4-af8a-7156f90d6885',
}

session = Session()
session.headers.update(headers)

try:
    while(True):
        response = session.get(url, params=parameters)
        data = json.loads(response.text)

        for entry in data["data"]:
            symbol = entry["symbol"]
            price1 = str(entry["quote"]["USD"]["price"])[:5]

        print(symbol + ':', price1)
        board.send_sysex(STRING_DATA, util.str_to_two_byte_iter(symbol))
        board.send_sysex(STRING_DATA, util.str_to_two_byte_iter(price1))
        time.sleep(30)
    except (ConnectionError, Timeout, TooManyRedirects) as e:
    print(e)
于 2021-12-28T23:50:32.890 回答