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)
4
  • Just import sys, like this: from sys import exit; import sys Commented May 9, 2015 at 20:54
  • 3
    you're using sys.argv, so clearly, you've imported sys. So just do sys.exit Commented May 9, 2015 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 ? Commented May 9, 2015 at 22:36
  • Does this answer your question? NameError: name 'exit' is not defined Commented Sep 2, 2022 at 10:53

2 Answers 2

6

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.

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

1 Comment

Bingo! Something about compiling complicates it; adding the sys. resolves that.
5

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.

2 Comments

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?
I can't get exit to work anywhere in a running Python3 program even if I import sys.

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.