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

callback function doesn't print, unless ran by 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 一直保持交互式 window 打开,甚至在您之后很长时间' ve 运行 代码 :)

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)