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
  • 14,700
  • 4
  • 41
  • 43
study
  • 333
  • 1
  • 5
  • 16
  • Just import sys, like this: from sys import exit; import sys – felipsmartins May 09 '15 at 20:54
  • 3
    you're using `sys.argv`, so clearly, you've imported `sys`. So just do `sys.exit` – inspectorG4dget May 09 '15 at 20:55
  • 1
    A quick question. I run it earlier with a super computer, and it works. But today I run it in my PC with canopy, it gives me an error like that. Does anyone know why ? – study May 09 '15 at 22:36
  • Does this answer your question? [NameError: name 'exit' is not defined](https://stackoverflow.com/questions/45066518/nameerror-name-exit-is-not-defined) – Hamza Zubair Sep 02 '22 at 10:53

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
  • 14,700
  • 4
  • 41
  • 43
  • 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,559
  • 5
  • 36
  • 48
user3760296
  • 121
  • 1
  • 4