8

The following is the code. When I run, I got an error message, saying that "name exit is not defined". Could anyone tell me why? Thanks very much for your time and attention.

if len(sys.argv) == 4:
   ### do something
    pass
else:
    print
    "usage: #### something here"
    exit(-1)
khampson
  • 13,812
  • 4
  • 39
  • 40
study
  • 323
  • 1
  • 4
  • 16

2 Answers2

6

You need to import sys first, since exit (and argv) is in that module.

The error I get when I run your code is:

File "", line 1, in NameError: name 'sys' is not defined

which is complaining about sys.argv instead of exit. But in either case, the solution -- import sys is the same.

khampson
  • 13,812
  • 4
  • 39
  • 40
  • 1
    Actually, even without `import sys` the `exit` command works in terminal. But when I'm running the same script from within Jupyter notebook, I need the import. Not sure why? – coder.in.me Sep 20 '16 at 15:24
  • I can't get exit to work anywhere in a running Python3 program even if I import sys. – rjurney Apr 25 '17 at 03:21
5

If you imported sys then use sys.exit(0) - change 0 with any result code you want to exit with. I had the same issue that before compilation when running from .py file exit(0) worked well but after compiling to .exe it gave me an error. I had to change exit(0) to sys.exit(0) and it worked.

tuomastik
  • 4,122
  • 5
  • 33
  • 44
user3760296
  • 121
  • 1
  • 4