【发布时间】:2022-11-01 17:18:18
【问题描述】:
我使用 for 循环创建了多个线程,我需要读取线程内的线程名称。我怎么做?我使用了 threading.Thread.name 但返回了线程对象的一些内存地址。这是我的代码的一部分:
def catch_sharp_fall(update, context, x):
global access_token, watchlist, bot, chat_id, market_open_alert, nifty, bot_reset, stop_catch_sharp_fall, \
kite_api_key
ins_code = x
kite = KiteConnect(kite_api_key)
kite.set_access_token(access_token)
kws = KiteTicker(kite_api_key, access_token)
def on_ticks(ws, ticks):
logging.debug("Ticks: {}".format(ticks))
def on_connect(ws, response):
ws.subscribe([ins_code])
ws.set_mode(ws.MODE_FULL, [ins_code])
def on_close(ws, code, reason):
ws.stop()
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
kws.connect(threaded=True)
while True:
def on_ticks(ws, ticks):
feed_data(ticks)
def feed_data(ticks):
list_of_threads_running = [i.name for i in threading.enumerate()]
logging.info(f'list of threads running {list_of_threads_running}')
# update.message.reply_text(f'<b>I am the stock {ins_code}</b>', parse_mode='HTML')
logging.info(f'{threading.Thread.name}')
kws.on_ticks = on_ticks
for x in watchlist:
t = threading.Thread(name=str(x), target=catch_sharp_fall, args=(update, context, x))
t.setDaemon(True)
t.start()
【问题讨论】:
-
线程并没有真正的名字。它们通常有 Thread-0 和 Thread-1。我建议在您的情况下查看线程池
-
threading.current_thread().name
标签: python python-multithreading