【问题标题】:How can I run the timer function in python bottle?如何在 python 瓶中运行计时器功能?
【发布时间】:2020-03-05 00:16:26
【问题描述】:

我想在 localhost 上打印 't' 和 's'。但它不适用于定时器功能。这是我尝试过的。

import requests
import pandas as pd
import time
from bottle import route, run

def timer(n):
    while True:
        url2 = 'https://api.bittrex.com/api/v1.1/public/getticker?market=USDT-BTC'
        res = requests.get(url2).json()
        BTC = pd.json_normalize(res['result'])
        t = time.ctime()
        s = BTC.to_html(index=False)
        time.sleep(n)
timer(5)

@route('/')
def index():
    return t, s
run(host='localhost', port=8080)

【问题讨论】:

  • def timer(n)
  • 你能比“它不起作用”更具体吗?

标签: python bottle


【解决方案1】:

如果没有关于究竟是什么不起作用的更多细节,很难给出全面的答案。但肯定需要改变的一件事是定义ts 的位置。正如@Pygirl 在她的评论中所说,您需要在全局范围内定义它们:

import requests
import pandas as pd
import time
from bottle import route, run

t = ''
s = ''

def timer(n):
    while True:
        url2 = 'https://api.bittrex.com/api/v1.1/public/getticker?market=USDT-BTC'
        res = requests.get(url2).json()
        BTC = pd.json_normalize(res['result'])

        # Must declare t and s as globals since you're changing their referents.
        global t
        global s
        t = time.ctime()
        s = BTC.to_html(index=False)

        time.sleep(n)

timer(5)

@route('/')
def index():
    return '{}: {}'.format(t, s)
run(host='localhost', port=8080)

全局定义它们的另一种方法是创建一个顶级字典,其中包含两个项目(ts),并根据需要简单地修改这些项目;在这种情况下不需要global

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多