简体   繁体   中英

sys.exit in python console

Hi I have troubles using sys.exit in a python console. It works really nice with ipython. My code looks roughly like this:

if name == "lin":
    do stuff
elif name == "static":
    do other stuff
else:
    sys.exit("error in input argument name, Unknown name")

If know the program know jumps in the else loop it breaks down and gives me the error message. If I use IPython everything is nice but if I use a Python console the console freezes and I have to restart it which is kind of inconvenient.

I use Python 2.7 with Spyder on MAC.

Is there a workaround such that I the code works in Python and IPython in the same way? Is this a spyder problem?

Thanks for help

Not sure this is what you should be using sys.exit for. This function basically just throws a special exception ( SystemExit ) that is not caught by the python REPL. Basically it exits python, and you go back to the terminal shell. ipython's REPL does catch SystemExit . It displays the message and then goes back to the REPL.

Rather than using sys.exit you should do something like:

def do_something(name):
    if name == "lin":
        print("do stuff")
    elif name == "static":
        print("do other stuff")
    else:
        raise ValueError("Unknown name: {}".format(name))

while True:
    name = raw_input("enter a name: ")
    try:
        do_something(name)
    except ValueError as e:
        print("There was a problem with your input.")
        print(e)
    else:
        print("success")
        break # exit loop

You need to import sys. The following works for me:

import sys
name="dave"
if name == "lin":
    print "do stuff"
elif name == "static":
    print "do other stuff"
else:
    sys.exit("error in input argument name, Unknown name")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM