python NameError: name '__file__' is not defined

kingcope picture kingcope · Jun 10, 2014 · Viewed 19.4k times · Source

i try compile this script whit py2exe :

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

setup script :

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"
        }
    ],)

after compile script, give this error :

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

where is the problem ?

Answer

Martijn Pieters picture Martijn Pieters · Jun 10, 2014

Scripts running under py2exe do not have a __file__ global. Detect this and use sys.argv[0] instead:

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]))