2

I'm coding a program which uses os.path.abspath(os.path.dirname(__file__))) to locate its config file and it works like a charm when I use it in pure Python, but as soon as I compile it to .exe using py2exe I get this error:

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

Exactly, line 17 is:

if os.path.isfile("%s/config.cfg" % os.path.abspath(os.path.dirname(__file__))):

Why this happens and how I can overcome this problem?

Thanks in advance! :)

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
Amar Kalabić
  • 888
  • 4
  • 15
  • 33
  • Here is probably the solution to your problem : http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python – s0h3ck May 20 '14 at 16:42

1 Answers1

2

The issue is that __file__ is set by the interpreter when you're running a file as input, but not when you run your py2exe'ed executable. You typically want to do something like this:

if hasattr(sys, 'frozen'):
  # retrieve path from sys.executable
  rootdir = os.path.abspath(os.path.dirname(sys.executable))
else:
  # assign a value from __file__
  rootdir = os.path.abspath(os.path.dirname(__file__))
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • That fixed thing. I understand it now, thanks for explanation! :) I'll mark ur answer as correct in 4 minutes (stackoverflow isn't allowing me to do it before)... Thanks again! – Amar Kalabić May 20 '14 at 16:38