Ask coding questions

← Back to all posts
sys.exit() not working in python repl?
richardnicholas

Hi all, I am not sure if this is a problem with repl.it or I am just coding the python wrong. My simple code to open a file is:

try:
file_in = open ('data_file', 'r')
except:
print ("Could not open data_file for reading.")
sys.exit(1)
print ("Why doesn't this exit work?")

All is well if data_file exists but if not, we go to the except where it does a print and should exit. But the program hangs there until I press Stop. The 2nd print statement does not occur either so it looks like it goes into exit() but does not come out?

Ideas? Thanks.

Edit to original question: I see the whitespace indentation got lost when I submitted the question but it is correct in the real code.

Voters
StellaCho
richardnicholas
Comments
hotnewtop
QuantumCodes

A simple exit() works for me

multicoder2021

I don't understand your problem but...

I don't really see a problem when I paste the code in another repl of mine, maybe it is a problem with something else, like WiFi or something, the code works just fine.

I don't see the problem

UnikaftUnikaft

@multicoder2021 i think what he means is that when the code runs exit() it says "repl process died unexpectedly: >"
i'm having the same problem.

multicoder2021

@UnikaftUnikaft If you don't want it to say repl process died unexpectedly, just use SystemExit().

It doesn't really exit though. It justs outputs >

multicoder2021

Wait... so do you want to exit the repl and then wait and enter it again?

multicoder2021

Here, I have the solution for the code:

E-Sheep

Try just exit()

timmy_i_chen

For future reference, you can paste a repl link here for easy reproduction ;)

sys.exit() is working, but the termination message probably isn't sent to the repl. This works in project mode (if you add another .py to take it out of eval mode):

https://repl.it/@timmy_i_chen/sys-exit

richardnicholas

@timmy_i_chen Thanks for the reply. I don't really understand why repl makes this distinction between "eval mode" and "project mode" and basing that on having 1 file or more than 1 file? And furthermore, you have limited capabilities unless you add a 2nd file? This seems like a bad idea... :-) Because now if I want exit() to get me back to the repl command prompt I have to add a 2nd file that I don't need in this case?

timmy_i_chen

@richardnicholas Eval mode and Project mode both have their drawbacks and benefits, detailed here: http://repl.it/site/docs/files

In this particular case, it should actually say "Repl died unexpectedly" or something similar - but we need to look into this to see what has regressed.