18

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 ?

kingcope
  • 1,121
  • 4
  • 19
  • 36

1 Answers1

32

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]))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • would you recommend using __ file __ or sys.argv[0] ? Is one the current working directory whereas the other __ file __ is the actual path to the file? – Har Jan 28 '16 at 11:19
  • @Har; `sys.argv[0]` is the path passed to Python. For modules *other than the script* it'll be the wrong path, so using `__file__` is more universal and flexible. – Martijn Pieters Jan 28 '16 at 11:21
  • Is the path passed to python by default the cwd? and by modules other than the script do you mean module which are meant to be imported? – Har Jan 28 '16 at 11:26
  • Any Python file can be used as a script or as a module you import. The `sys.argv[0]` filename only applies to the script. That path is not necessarily the `os.getcwd()` value; that could be something else still. – Martijn Pieters Jan 28 '16 at 11:35