python NameError:未定义名称"__file__"

kin*_*ope 16 python py2exe

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

import os 
file1 = os.path.dirname(os.path.realpath('__file__'))
file2 = os.path.realpath(__file__)
Run Code Online (Sandbox Code Playgroud)

设置脚本:

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"
        }
    ],)
Run Code Online (Sandbox Code Playgroud)

编译脚本后,给出以下错误:

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

问题出在哪儿 ?

Mar*_*ers 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]))
Run Code Online (Sandbox Code Playgroud)