Python NameError: name 'exit' 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45066518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:40:04  来源:igfitidea点击:

NameError: name 'exit' is not defined

pythoncx-freeze

提问by Tim

I used cxfreeze to create a Windows executable from planrequest.py. It seemed to work ok, but when I run the exe file I get NameError: name 'exit' is not defined

我使用 cxfreeze 从 planrequest.py 创建了一个 Windows 可执行文件。它似乎工作正常,但是当我运行 exe 文件时,我得到NameError: name 'exit' is not defined

name exit is not defined in pythonstates that the fix is to use import sys. However, I use import sys. The code runs fine as a python script (as in, I extensively tested the command line arguments before compiling to an executable.)

名称退出未在 python状态中定义,修复是使用import sys. 但是,我使用 import sys. 该代码作为 python 脚本运行良好(例如,在编译为可执行文件之前,我广泛测试了命令行参数。)

import socket
import sys

if len(sys.argv) == 1:
    print("Usage:")
    print("PlanRequest [Request String] [Server IP (optional: assumes 127.0.0.1 if omitted)]")
    exit()

#[do stuff with the request]

采纳答案by b1ch0u

Importing sys will not be enough to make exitlive in the global scope.

导入 sys 不足以exit在全局范围内生效。

You either need to do

你要么需要做

from sys import exit
exit()

or

或者

import sys
sys.exit()

Note that, as you are also using argv, in the first case you should dofrom sys import argv,exit

请注意,由于您也在使用 argv,因此在第一种情况下您应该这样做from sys import argv,exit

回答by Damián Rafael Lattenero

You have to apply the function to sys:

您必须将该函数应用于 sys:

from sys import exit
exit()

because exitis the function itself, you need to call it with ()

因为exit是函数本身,你需要调用它()