I have the following code in a .py file that is run in Spyder as a test:
print('Hello World')
exit()
when this code is copied into the iPython console it works fine but when I run the file using run button I get the following error:
%runfile /Users/Sam/Downloads/untitled1.py --wdir
Hello World
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
File ~/opt/anaconda3/lib/python3.10/site-packages/spyder_kernels/customize/utils.py:209, in exec_encapsulate_locals(code_ast, globals, locals, exec_fun, filename)
207 if filename is None:
208 filename = "<stdin>"
--> 209 exec_fun(compile(code_ast, filename, "exec"), globals, None)
210 finally:
211 if use_locals_hack:
212 # Cleanup code
File ~/Downloads/untitled1.py:9
3 """
4 Created on Mon Mar 17 22:17:47 2025
5
6 @author: Sam
7 """
8 print('Hello World')
----> 9 exit()
NameError: name 'exit' is not defined
The exit() function is working just fine in Spyder's iPython console (and in terminal) but not when used in a file that is then run from Spyder. I know I can use the sys.exit() function but would quite like to understand why there is this difference.