【问题标题】:How to evualate a function in a while loop如何在while循环中评估函数
【发布时间】:2020-10-29 11:16:33
【问题描述】:

我试图在比较两个值时实时流式传输数据。但是,似乎该函数只被评估一次。但是,time.sleep 也在运行,因为它在循环之间暂停。但是时间总是一样的。

x = f'https://api.polygon.io/v1/last/stocks/SPY?{key}'
def get_data():
    time.sleep(5)
    data = requests.get(x)
    json_data = data.json()
    
    #last price, datetime object
    print ((json_data['last'])['price'], epoch_to_date_time( (json_data['last'])['timestamp'] ).__str__())
    return (json_data['last'])['price']


def while_no_match(x):
    counter = 0
    while get_data()!=x and counter < 5 :
        get_data()
        counter +=1

if __name__ == '__main__':
    while_no_match(100)
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000

【问题讨论】:

  • 如何不出现名称错误?
  • x 是我正在使用的 API 的链接。另外,感谢您的提示。
  • 你是对的。它可能是API。在市场交易时间我没有遇到这个问题。删除反对票会很好。寻求帮助已经够难的了。

标签: python-3.x while-loop python-requests sleep


【解决方案1】:

手动运行 get_data 几次后,我收到以下输出:

316.69 2020-07-08 19:36:39.535000
316.71 2020-07-08 19:37:07.138000
316.71 2020-07-08 19:37:07.138000

它必须是 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多