Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python NameError: name '__file__' is not defined [duplicate]

Tags:

python

py2exe

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 ?

like image 439
kingcope Avatar asked Jun 10 '14 12:06

kingcope


1 Answers

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]))
like image 193
Martijn Pieters Avatar answered Sep 28 '22 03:09

Martijn Pieters