Thread 사용 중, ValueError: signal only works in main thread 오류

조회수 2135회

Thread 과 pytchat 을 이용하여 유튜브 라이브 채팅을 불러옴과 동시에, 다른 일을 수행하고 싶습니다.

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()

오류는 다음과 같이 나오는 데, 어떻게 해결해야할 지 모르겠습니다..

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
  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 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: #멀티프로세싱
            with Pool(5) as p:
                t = p.map(f, [1, 2, 3])
                print(t)
        except Exception as e:
            print(e)
    
        try: #쓰레드
            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
    

    말그대로 signal 은 메인스레드에서만 실행가능합니다. 병렬처리하려는것을 스레드로 옮기거나 pychat 을 멀티프로세싱으로 돌려주세요

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)