Search code examples
pythonexitraspberry-pi2

How to exit python program on raspberry


My program in python runs on RaspBerry Pi, and instantiates several objects (GPIO inputs and outputs, http server, webSocket, I2C interface, etc..., with thread).

When exiting my program, I try to clear all the resources, and delete all the instances. For the network objects, I close listening sockets and so on. I finish with a sys.exit() call, but program doe not exit and does not returns alone to linux console (I need to press ctrl+z).

Are there some objects that are not released, how to know, and how to force exit ?

Best regards.


Solution

  • I'm programming for Raspberry Pi with the Kivy library, and I've had a similar problem. The comments in this topic have helped me solve it.

    In my case, Kivy uses "Clock()" objects to call a function with certain time intervals, providing the main program loop.

    As it turns out, while everything works fine on a PC (in Linux or Windows), on Raspberry Pi you have to manually stop all program loops, otherwise "sys.exit()" will not work.

    At first, I had "sys.exit()" command executing at key press. That didn't work for Raspberry. So, instead I used a global variable that would change value when the exit key is pressed, and had its value checked within the program loop, where I then called "sys.exit()" (and "return False", which signals Kivy to destroy the Clock() object).

    I've also been using separate Clock() objects for some animations in my program, and I've noticed that if I press exit while an animation is running, my program would freeze without exiting - just as before, because "sys.exit()" was called while some Clock() objects were running.

    The bottom line is - if you have trouble with "sys.exit()" on Raspberry Pi, make sure all program loops in your code are stopped before calling sys.exit().

    As the most simple example, if you have a program running a loop like

    while True:
    

    instead use

    while running:
       # where running = True
    

    then change to "running = False" before calling "sys.exit()".