I am using Spyder 6 console to invoke a Python script via the runfile
command. After a recent Anaconda update, I found that sys.exit()
no longer exits the script quietly. It prints:
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0
C:\Users\User.Name\AppData\Local\anaconda3\envs\py39\lib\site-packages\IPython\core\interactiveshell.py:3534: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
Using exit()
and quit()
are equally verbose.
I came across suggestions to use sys.exit(0)
, but it doesn't change anything for me. I want to avoid os._exit()
because it skips cleanup handlers.
How would I gracefully and quietly exit a script that is called with runfile
?
Following up on ticktalk's comment, I ran the script outside of Spyder to see what the termination message looked like. It took a while to figure out how to do this using exec(open("FileName.py").read())
.
I tried this alternative from IPython, i.e., issuing ipython3
from the anaconda prompt. The output from exec
is the same as Spyder's above. I'm not surprised because I thought that Spyder uses IPython in the back end.
I also tried the REPL that results from issuing python
from the Anaconda prompt. The exec
command yielded no messages when the script terminates due to sys.exit()
.
Conclusion: The messages are due to IPython. Since I'm heavily reliant on Spyder, the only method currently to avoid them is Ben A.'s answer below. It requires that the whole script by wrapped in a function which requires indentation and shortens the usable source code line width. I may still go with that.
Perhaps you are overlooking a more obvious answer.
def main():
# blah blah
if want_to_leave_quietly:
return #no mess
if __name__ == "__main__":
main()