python打包后,执行报错:NameError: name ‘exit‘ is not defined

个人知识库

Author: 刘杰文, Date: Unknown, Categories: , Tags:

python打包后,执行报错:NameError: name ‘exit‘ is not defined

出现问题的伪代码如下:

try:
    file_name = os.path.basename(src)
    file_size = os.stat(src).st_size
except Exception:
    print("源文件不存在:", src)
    exit()

在ide使用中没有问题,但是封装成应用程序时就出现问题:

online picture

NameError: name 'exit' is not defined

百度了一圈后解决办法如下:将exit(),改为sys.exit()

import sys

   try:
        file_name = os.path.basename(src)
        file_size = os.stat(src).st_size
    except Exception:
        print("源文件不存在:", src)
        sys.exit()

Python 中的 exit() 和 sys.exit() 的区别

现在来了解下 Python 中的 exit()sys.exit()

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

上面的意思是 exit 用于给交互式 Shell 返回值,而 sys.exit 是用于程序内部。


版权声明:本文为CSDN博主「马克图布s」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/weixin_44214830/article/details/118337774