Using Thread, ValueError: signal only works in main thread error

Asked 2 years ago, Updated 2 years ago, 68 views

I would like to do something else while calling YouTube live chat using Thread and pythchat.

def chat_get():
    global ytloc
    ytloc="https://www.youtube.com/watch?v=GoXPbGQl-uQ"
    print(ytloc)
    chat = pytchat.create(video_id=ytloc)

    while True:        
        if chat.is_alive():
            for c in chat.get().sync_items():
                 print(f"{c.datetime} [{c.author.name}] {c.message}")

        time.sleep(1)
temp=Thread(target=chat_get)
temp.start()

The error appears as follows, but I don't know how to resolve it.

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\th070\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\th070\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\th070\Desktop\youtube_livechat_viewer\live_viewer.py", line 28, in chat_get
    chat = pytchat.create(video_id=ytloc)
  File "C:\Users\th070\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pytchat\core\__init__.py", line 7, in create
    return PytchatCore(_vid, **kwargs)
  File "C:\Users\th070\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pytchat\core\pytchat.py", line 89, in __init__
    signal.signal(signal.SIGINT, lambda a, b: self.terminate())
  File "C:\Users\th070\AppData\Local\Programs\Python\Python38-32\lib\signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

thread threading error

2022-09-20 15:52

1 Answers

from multiprocessing import pool
from threading import Thread
import signal

def f(x=555):
    def handler(num, f):
        print("SIGNAL")

    try:
        signal.signal(signal.SIGINT, handler)
        signal.raise_signal(signal.SIGINT)
        print(x)
        return x*x
    except Exception as e:
        print(e) #signal only works in main thread
        return 1


if __name__ == '__main__':
    try: #multiprocessing
        with Pool(5) as p:
            t = p.map(f, [1, 2, 3])
            print(t)
    except Exception as e:
        print(e)

    try: #Thread
        q = Thread(target = f)
        q.start()
    except Exception as e:
        print(e)

SIGNAL
1
SIGNAL
2
SIGNAL
3
[1, 4, 9]
signal only works in main thread

Literally, signal can only be executed on the main thread. Move what you want to parallelize to thread or return pychat to multiprocessing


2022-09-20 15:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.