3

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.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
harry
  • 101
  • 3
  • 11
  • Was the error `NameError: global name 'sys' is not defined`? Calling `sys.exit()` exits cleanly for me. – Abe Karplus Aug 03 '12 at 03:02
  • 7
    The traceback error only exists in IDLE, that is the correct way to exit a program. – Josiah Aug 03 '12 at 03:02
  • Alright thank you that was what I was trying to get at cause I wasn't sure if it was poor coding to do a sys.exit() and if it causes issues. – harry Aug 03 '12 at 03:06
  • @harry next time, you should show the traceback error along with your question.. helps diagnose the problem sooner. Cheers. – Josh Smeaton Aug 03 '12 at 03:16
  • 1
    @Josh Will do sorry about im still getting use to this awesome website! – harry Aug 03 '12 at 03: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. – Josiah Aug 03 '12 at 03:21
  • You can throw away the `sys` part and just use `exit()` which is the same function (this is apparently undocumented, or at least I can't find documentation for this, but it's been like this since at least python 2.5). – l4mpi Aug 03 '12 at 10:53
  • 1
    @l4mpi No, it is slightly different. `sys.exit` is a ``, but `exit` is a `` object. – glglgl Jun 25 '13 at 16:59

2 Answers2

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)

rafa
  • 795
  • 1
  • 8
  • 25
1

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

add this before the sys.exit() line :

import sys
Mohamed Benkedadra
  • 1,964
  • 3
  • 21
  • 48
iammgt
  • 43
  • 1
  • 10