Issue
To interrupt the code at defined positions I place in the code the command sys.exit()
.
The program stops but does not return the stopping position. Neither in the console nor in the code window I see at which point the program has stopped. As I have several stop commands I do not know where the program has exited and I become completely lost in the code.
Is this a bug? How can I stop programmatically a code with output of the position? What is the fastest way?
I use Spyder 5.1.5 and Spyder 5.2 with WinPython 3.9.5.0 and the programs are used without installation on Win10Pro version 21H1.
Solution
sys.exit()
without any parameter just terminates the execution without any further information.
If you need to see witch sys.exit
line was called you have several options. Here are 2 simple solutions for that.
1°) The simple way
sys.exit()
accept a parameter. When you pass a string, this string will be printed on exit. You can take advantage of this to trace witch exit point was used.
Example:
if True:
sys.exit("exit point 1")
else:
sys.exit("exit point 2")
will print the folling when executed:
exit point 1
This is very straighforward but needs to make a full pass on your code to change all sys.exit
calls. Luckily there is a less intrusive option.
2°) Using SystemExit
exception
sys.exit()
, ultimatly raises a SystemExit
exception. As every other exception it can be catched, so you can then print the call stack using the traceback
module.
All you have to do is surrounding you main program with a try:
except SystemExit:
to intercept the sys.exit()
call and print the call stack.
Here is a simple example : import sys import traceback
def test():
print ("entering test")
sys.exit()
print ("leaving test")
try:
test()
sys.exit()
except SystemExit as e:
traceback.print_exc()
raise e
The output of this program will be:
entering test
Traceback (most recent call last):
File "test.py", line 10, in <module>
test()
File "test.py", line 6, in test
sys.exit()
SystemExit
So you can see you exited through the line 6 of file test.py
The behavior is well documented on the python standard library documentation : https://docs.python.org/3/library/sys.html (chapter sys.exit)
Answered By - Frédéric Branca
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.