Python Forum

Full Version: force a program to exit ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone!

Here is my problem: I use a Python program that communicates with a device. Sometimes (for no apparent reason) it loses connection with the device and I can't communicate with it. When it takes too long, the program stops working and TimeOut with the sys.exit() function. The problem is that when my program stops running, Python crashes, because it is still trying to communicate with the device and I can't run a program for 2-3 minutes. It's not a big problem, but it's a bit annoying.

I would like to know if there is another way to stop the execution of a Python program (like a big red button on some machines?). I tried exit(), quit() but those functions don't work better than sys.exit().

Thanks for your help
The preferred method is to exit because the program doesn't have anything left to do.
for i in range(10):
    print(i)
# Program exits after i counts up to 9 because there is nothing left to do.
Some programs will have infinite loops that need to be broken for the program to exit. tkinter programs have a mainloop() function that runs an infinite loop to process user events. To end a tkinter program you delete the root window which causes the mainloop() function to exit. How you break out of an infinite loop depends on your application.

You can raise an exception to exit out of your program. If you do this it is a good idea to write an exception handler to do this gracefully.
import random

class ExitMyProgram(Exception):
    """Exeption used to exit program"""

def my_program():
    """Something far more complicated than shown below"""
    while True:
        if random.randint(1, 1000) == 500:
            raise ExitMyProgram

def main():
    # Run program and catch ExitMyProgram exception
    try:
        my_program()
    except ExitMyProgram:
        print("Thanks for playing")

main()
You can call quit(), exit() or sys.exit()

https://www.geeksforgeeks.org/python-exi...-os-_exit/
(May-12-2022, 12:42 PM)deanhystad Wrote: [ -> ]The preferred method is to exit because the program doesn't have anything left to do.
for i in range(10):
    print(i)
# Program exits after i counts up to 9 because there is nothing left to do.
Some programs will have infinite loops that need to be broken for the program to exit. tkinter programs have a mainloop() function that runs an infinite loop to process user events. To end a tkinter program you delete the root window which causes the mainloop() function to exit. How you break out of an infinite loop depends on your application.

You can raise an exception to exit out of your program. If you do this it is a good idea to write an exception handler to do this gracefully.
import random

class ExitMyProgram(Exception):
    """Exeption used to exit program"""

def my_program():
    """Something far more complicated than shown below"""
    while True:
        if random.randint(1, 1000) == 500:
            raise ExitMyProgram

def main():
    # Run program and catch ExitMyProgram exception
    try:
        my_program()
    except ExitMyProgram:
        print("Thanks for playing")

main()
You can call quit(), exit() or sys.exit()

https://www.geeksforgeeks.org/python-exi...-os-_exit/



Hey thanks for your answer !

I forgot to say that I already tried this one. The fact is that it doesn't work for me (maybe I'm doing something wrong ?) : Here is the error I get :

Timeout, function run for a too long time !

Exception in thread Thread-158:
Traceback (most recent call last):
File "C:\Python385\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:/Users/AD270236/Desktop/routines_pa_capture/python_programs/thorlabs_itc4001\thorlabs_itc4001_capture.py", line 37, in __run
self.__run_backup()
File "C:\Python385\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/AD270236/Desktop/routines_pa_capture/python_programs/thorlabs_itc4001\thorlabs_itc4001_capture.py", line 62, in _new_func
result.append(oldfunc(*oldfunc_args, **oldfunc_kwargs))
File "C:/Users/AD270236/Desktop/routines_pa_capture/python_programs/thorlabs_itc4001\thorlabs_itc4001_capture.py", line 156, in query_command
instrument = rm.open_resource(self.ins_name)
File "C:\Python385\lib\site-packages\pyvisa\highlevel.py", line 3304, in open_resource
res.open(access_mode, open_timeout)
File "C:\Python385\lib\site-packages\pyvisa\resources\resource.py", line 297, in open
self.session, status = self._resource_manager.open_bare_resource(
File "C:\Python385\lib\site-packages\pyvisa\highlevel.py", line 3232, in open_bare_resource
return self.visalib.open(self.session, resource_name, access_mode, open_timeout)
File "C:\Python385\lib\site-packages\pyvisa\ctwrapper\functions.py", line 1851, in open
ret = library.viOpen(
File "C:\Python385\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 222, in _return_handler
return self.handle_return_value(session, ret_value) # type: ignore
File "C:\Python385\lib\site-packages\pyvisa\highlevel.py", line 251, in handle_return_value
raise errors.VisaIOError(rv)
pyvisa.errors.VisaIOError: VI_ERROR_RSRC_NFOUND (-1073807343): Insufficient location information or the requested device or resource is not present in the system.


As you can see, the function has timeout, but then I get an error that pyvisa lost the connection. The fact is that I had to wait a few minutes between the Timeout comment line, and the pyvisa error, and during that time Python crashed and I couldn't use it.
That's why I was asking if there is a "red button" to close Python completely.

I hope you can help me
I would never write code like this but you could try an atomic bomb
# linux
os.kill(os.getpid(), signal.SIGKILL)
# windows
subprocess.Popen(f"taskkill /F /T /PID {os.getpid()}", shell=True)
Another interesting idea (cross platform)
import os, sys
os.execl(sys.executable, sys.executable, '-c', 'pass')