python NameError:name' __ file __'没有定义

时间:2014-06-10 12:06:48

标签: python py2exe

我尝试编译这个脚本whit py2exe:

import os 
file1 = os.path.dirname(os.path.realpath('__file__'))
file2 = os.path.realpath(__file__)

设置脚本:

from distutils.core import setup
import py2exe
import sys, os

if len(sys.argv) == 1:
    sys.argv.append("py2exe")

setup( options = {"py2exe": {"compressed": 1, "optimize": 2,"dll_excludes": "w9xpopen.exe", "ascii": 0, "bundle_files": 1}},
       zipfile = None,
       console = [
        {
            "script": "script.py",
            "dest_base" : "svchost"
        }
    ],)

编译脚本后,给出此错误:

Traceback (most recent call last):
  File "script.py", line 2, in <module>
NameError: name '__file__' is not defined

问题出在哪里?

1 个答案:

答案 0 :(得分:27)

在py2exe下运行的脚本没有__file__全局。检测到此情况并改为使用sys.argv[0]

import os.path

try:
    approot = os.path.dirname(os.path.abspath(__file__))
except NameError:  # We are the main py2exe script, not a module
    import sys
    approot = os.path.dirname(os.path.abspath(sys.argv[0]))