在 Python 中重复执行函数的最佳方法是什么?
What is the best way to repeatedly execute a function in Python?
我正在尝试从网站中提取一些数据。我遇到的问题是它提取数据值,然后继续不断地重新打印它,而不是提取最新的实时数据值并更新它。我从 https://github.com/BitMEX/api-connectors/tree/master/official-ws/python 获得了代码并做了一些更改。
from bitmex_websocket import BitMEXWebsocket
import logging
from time import sleep
# Basic use of websocket.
def run():
logger = setup_logger()
# Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
ws = BitMEXWebsocket(endpoint="https://www.bitmex.com/api/v1", symbol="XBTUSD",
api_key=None, api_secret=None)
logger.info("Instrument data: %s" % ws.get_instrument())
# Run forever
while(ws.ws.sock.connected):
logger.info("Ticker: %s" % ws.get_ticker())
if ws.api_key:
logger.info("Funds: %s" % ws.funds())
#logger.info("Market Depth: %s" % ws.market_depth())
(logger.info("Recent Trades: %s\n\n" % ws.recent_trades()[0]["size"]))
sleep(1)
def setup_logger():
# Prints logger info to terminal
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Change this to DEBUG if you want a lot more info
ch = logging.StreamHandler()
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
if __name__ == "__main__":
run()
问题是您在 while 循环内的 ws.get_ticker()
调用实际上并未获得更新值。
def get_ticker(self):
'''Return a ticker object. Generated from quote and trade.'''
lastQuote = self.data['quote'][-1] # <--SEE HERE. It's just getting the
lastTrade = self.data['trade'][-1] # information from when the ticker was
# first established.
ticker = {
"last": lastTrade['price'],
"buy": lastQuote['bidPrice'],
"sell": lastQuote['askPrice'],
"mid": (float(lastQuote['bidPrice'] or 0) + float(lastQuote['askPrice'] or 0)) / 2
}
# The instrument has a tickSize. Use it to round values.
instrument = self.data['instrument'][0]
return {k: round(float(v or 0), instrument['tickLog']) for k, v in ticker.items()}
参见 my 注释,其中定义了 lastQuote
和 lastTrade
。您应该在每次循环后重新创建 ws
。如果您想永远这样做,则必须将 while 循环中的条件更改为 while True
。
from bitmex_websocket import BitMEXWebsocket
import logging
from time import sleep
# Basic use of websocket.
def run():
logger = setup_logger()
logger.info("Instrument data: %s" % ws.get_instrument())
# Run forever
while True:
# Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
ws = BitMEXWebsocket(endpoint="https://www.bitmex.com/api/v1", symbol="XBTUSD",
api_key=None, api_secret=None)
logger.info("Ticker: %s" % ws.get_ticker())
if ws.api_key:
logger.info("Funds: %s" % ws.funds())
#logger.info("Market Depth: %s" % ws.market_depth())
(logger.info("Recent Trades: %s\n\n" % ws.recent_trades()[0]["size"]))
ws.exit()
sleep(1)
def setup_logger():
# Prints logger info to terminal
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Change this to DEBUG if you want a lot more info
ch = logging.StreamHandler()
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
if __name__ == "__main__":
run()
编辑:在 while 循环中添加了对 ws.exit()
的调用,以便在打开新循环之前优雅地关闭 ws
。
我正在尝试从网站中提取一些数据。我遇到的问题是它提取数据值,然后继续不断地重新打印它,而不是提取最新的实时数据值并更新它。我从 https://github.com/BitMEX/api-connectors/tree/master/official-ws/python 获得了代码并做了一些更改。
from bitmex_websocket import BitMEXWebsocket
import logging
from time import sleep
# Basic use of websocket.
def run():
logger = setup_logger()
# Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
ws = BitMEXWebsocket(endpoint="https://www.bitmex.com/api/v1", symbol="XBTUSD",
api_key=None, api_secret=None)
logger.info("Instrument data: %s" % ws.get_instrument())
# Run forever
while(ws.ws.sock.connected):
logger.info("Ticker: %s" % ws.get_ticker())
if ws.api_key:
logger.info("Funds: %s" % ws.funds())
#logger.info("Market Depth: %s" % ws.market_depth())
(logger.info("Recent Trades: %s\n\n" % ws.recent_trades()[0]["size"]))
sleep(1)
def setup_logger():
# Prints logger info to terminal
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Change this to DEBUG if you want a lot more info
ch = logging.StreamHandler()
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
if __name__ == "__main__":
run()
问题是您在 while 循环内的 ws.get_ticker()
调用实际上并未获得更新值。
def get_ticker(self):
'''Return a ticker object. Generated from quote and trade.'''
lastQuote = self.data['quote'][-1] # <--SEE HERE. It's just getting the
lastTrade = self.data['trade'][-1] # information from when the ticker was
# first established.
ticker = {
"last": lastTrade['price'],
"buy": lastQuote['bidPrice'],
"sell": lastQuote['askPrice'],
"mid": (float(lastQuote['bidPrice'] or 0) + float(lastQuote['askPrice'] or 0)) / 2
}
# The instrument has a tickSize. Use it to round values.
instrument = self.data['instrument'][0]
return {k: round(float(v or 0), instrument['tickLog']) for k, v in ticker.items()}
参见 my 注释,其中定义了 lastQuote
和 lastTrade
。您应该在每次循环后重新创建 ws
。如果您想永远这样做,则必须将 while 循环中的条件更改为 while True
。
from bitmex_websocket import BitMEXWebsocket
import logging
from time import sleep
# Basic use of websocket.
def run():
logger = setup_logger()
logger.info("Instrument data: %s" % ws.get_instrument())
# Run forever
while True:
# Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
ws = BitMEXWebsocket(endpoint="https://www.bitmex.com/api/v1", symbol="XBTUSD",
api_key=None, api_secret=None)
logger.info("Ticker: %s" % ws.get_ticker())
if ws.api_key:
logger.info("Funds: %s" % ws.funds())
#logger.info("Market Depth: %s" % ws.market_depth())
(logger.info("Recent Trades: %s\n\n" % ws.recent_trades()[0]["size"]))
ws.exit()
sleep(1)
def setup_logger():
# Prints logger info to terminal
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Change this to DEBUG if you want a lot more info
ch = logging.StreamHandler()
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
if __name__ == "__main__":
run()
编辑:在 while 循环中添加了对 ws.exit()
的调用,以便在打开新循环之前优雅地关闭 ws
。