回调函数不打印,除非由 Jupyter 运行



以下是重现问题所需的最少代码。

我用一个回调函数调用API,该函数打印API调用的结果。

如果我在Jupyter中运行这段代码,就会得到输出。如果我用python file.py运行它,我不会得到任何输出。我已经检查了API的代码,但这并没有什么奇怪的。将DEBUGGING设置为True也没有帮助。

注意,有一次依赖;Bitvavo API。用pip install python-bitvavo-api安装

# %%
from python_bitvavo_api.bitvavo import Bitvavo
# %%
def generic_callback(response):
print(f"log function=get_markets, {response=}")
bitvavo = Bitvavo({"DEBUGGING": False})
websocket = bitvavo.newWebsocket()
# %%
websocket.markets(options={"market": "BTC-EUR"}, callback=generic_callback)

以下是我从Jupyter获得的预期输出:

log function:get_markets, response={'market': 'BTC-EUR', 'status': 'trading', 'base': 'BTC', 'quote': 'EUR', 'pricePrecision': 5, 'minOrderInBaseAsset': '0.0001', 'minOrderInQuoteAsset': '5', 'orderTypes': ['market', 'limit', 'stopLoss', 'stopLossLimit', 'takeProfit', 'takeProfitLimit']}

因为您使用的是websocket,回调由另一个线程执行,这意味着如果您不等待,主线程(接收print的输出(将已经被杀死。

在末尾添加一个sleep(1)(这是秒,而不是毫秒(,输出就会显示出来。

PS:Jupyter之所以显示输出,是因为Jupyter始终保持交互式窗口打开,即使在您运行代码很久之后:(

import time
from python_bitvavo_api.bitvavo import Bitvavo
# %%
def generic_callback(response):
print(f"log function=get_markets, {response=}")
bitvavo = Bitvavo({"DEBUGGING": False})
websocket = bitvavo.newWebsocket()
# Wait N.1 required to receive output, otherwise the main thread is killed
time.sleep(1)
# %%
websocket.markets(options={"market": "BTC-EUR"}, callback=generic_callback)
# Wait N.2 required to receive output, otherwise the main thread is killed
time.sleep(1)

最新更新