8

我想在后台运行一个函数。所以我在我的代码中使用线程。

但返回错误ValueError: signal only works in main thread并且不知道两件事:

  1. 主线是什么
  2. 如何解决这个问题呢 :)

views.py

def callback(update):
    print('I received', update)

def message_poll_start():
    try:
        client = TelegramClient('phone', api_id, api_hash,
            update_workers=1, spawn_read_thread=False)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass

def message_poll_start_thread(request):
    t = threading.Thread(target=message_poll_start, args=(), kwargs={})
    t.setDaemon(True)
    t.start()
    return HttpResponse("message polling started")

urls.py

urlpatterns = [
    path('message_poll_start', messagemanager_views.message_poll_start_thread, name="message_poll_start"),
]

trace

[12/Jan/2018 11:24:38] "GET /messages/message_poll_start HTTP/1.1" 200 23
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/teletogram/telethogram/messagemanager/views.py", line 123, in message_poll_start
    client0.idle()
  File "/home/teletogram/.env/lib/python3.5/site-packages/telethon/telegram_bare_client.py", line 825, in idle
    signal(sig, self._signal_handler)
  File "/usr/lib/python3.5/signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread
4

1 回答 1

10

1) 默认情况下,python 脚本在主线程中运行。如果您使用 生成一个新线程threading.Thread,那将创建一个与主线程分开运行的新线程。当我开始学习线程时,我花了很多时间阅读它才开始点击。官方的线程文档对于基本功能来说是不错的,我喜欢这个教程来更深入地了解。

2) Telethon 的内部依赖于 asyncio。在 asyncio 中,每个线程都需要自己的异步事件循环,因此产生的线程需要显式创建的事件循环。与线程一样,异步是一个很大的话题,其中一些在Telethon 文档中有所介绍。

像这样的东西应该工作:

import asyncio
def message_poll_start():
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        client = TelegramClient('phone', api_id, api_hash, loop=loop)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass
于 2019-05-27T19:16:58.823 回答