4

Heres the scenario I have a password that must be entered if entered wrong the script will not proceed and just exit itself? But how can I tell the script to safely exit itself?

I tried sys.exit() but that gives a traceback error and doesn't seem like a very clean exit method.

8
  • Was the error NameError: global name 'sys' is not defined? Calling sys.exit() exits cleanly for me. Commented Aug 3, 2012 at 3:02
  • 7
    The traceback error only exists in IDLE, that is the correct way to exit a program. Commented Aug 3, 2012 at 3:02
  • 1
    @Josh Will do sorry about im still getting use to this awesome website! Commented Aug 3, 2012 at 3:17
  • 1
    Oh right, one more thing. The reason that exists in IDLE is because IDLE catches and traces all exceptions, and sys.exit() throws an exception. This won't be that big of a deal for you unless you try to put it into a try: except: pass (which is bad practice anyways) where it will fail to exit the program. Commented Aug 3, 2012 at 3:21
  • 1
    @l4mpi No, it is slightly different. sys.exit is a <built-in function exit>, but exit is a <class 'site.Quitter'> object. Commented Jun 25, 2013 at 16:59

2 Answers 2

2

In fact, sys.exit() will only throw a SystemExit exception, which would make the program exit if this exception wasn't catched, but I don't think it's poor coding.

Anyway, another possibility is to use os._exit(0) if you need to exit immediately at any cost. (cf. http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit)

Sign up to request clarification or add additional context in comments.

Comments

1

you are using the sys module, but you haven't imported it.

add this before the sys.exit() line :

import sys

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.