1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why does exception stops the main loop despite having try-except block?

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I have the following code:

    import datetime
    import logging
    import time

    import pychromecast

    logging.basicConfig(level=logging.INFO, format="%(threadName)s:%(message)s")


    def run():
    id = 'sony kd-49xh8505'
    cast = pychromecast.get_chromecast_from_host(
    host=("192.168.86.126", None, id, id, id)
    )
    cast.wait()
    logging.info(cast.status.display_name)


    while True:
    print(datetime.datetime.now())
    try:
    run()
    except Exception as e:
    print("recovering")
    time.sleep(0.5)


    As you can see, I want to check every 0.5 second what app is running on my TV using PyChromecast. I want to ignore all errors and proceed with the loop.

    The sample output is:
    2024-09-15 19:33:48.253462
    MainThread:YouTube
    2024-09-15 19:33:49.171936
    MainThread:YouTube
    2024-09-15 19:33:50.165728
    MainThread:YouTube
    2024-09-15 19:33:51.090723
    Thread-38:[(192.168.86.126):8009] Failed to connect to service HostServiceInfo(host='192.168.86.126', port=8009), retrying in 5.0s


    So the app if working fine, then some connection error occurs and the app stops. The while True loop stops. What's interesting:

    • the main loop stops, but doesn't breaks (the app process is still active), but no further actions are performed
    • I have try-except: print("recovering"), but this message is not in the output
    • the log "Failed to connect to service" originates in a different thread - "Thread-38" - instead of "MainThread". Note also that the message says "retrying in 5.0s", but nothing happens after 5 seconds.

    Could you please explain what's happening here and - even more important - how to modify my app to ignore all connection errors and simply proceed with the main loop?

    Continue reading...

Compartilhe esta Página