py2exe 沒有 __file__ 可以使用，替代解法：
Here is the py2exe documentation reference and here are the relevant items:
sys.executableis set to the full pathname of the exe-file.
- The first item in
sys.argvis the full pathname of the executable, the rest are the command line arguments.
sys.frozenonly exists in the executable. It is set to “console_exe” for a console executable, to “windows_exe” for a console-less gui executable, and to “dll” for a inprocess dll server.
__file__is not defined (you might want to use sys.argv instead)
It is not apparent from those docs whether “the exe-file” and “the executable” are the same thing, and thus whether
sys.argv are the same thing. Looking at code that worked for both script.py and py2exe_executable.exe last time I had to do this, I find something like:
if hasattr(sys, 'frozen'): basis = sys.executable else: basis = sys.argv required_folder = os.path.split(basis)
As I say that worked, but I don’t recall why I thought that was necessary instead of just using
basis was adequate for the job in hand (read files in that directory). For a more permanent record, split something like
Update Actually did a test; beats guesswork and armchair pontification 🙂
Summary: Ignore sys.frozen, ignore sys.executable, go with sys.argv unconditionally.
=== foo.py ===
# coding: ascii import sys, os.path print 'sys has frozen:', hasattr(sys, 'frozen') print 'using sys.executable:', repr(os.path.dirname(os.path.realpath(sys.executable))) print 'using sys.argv:', repr(os.path.dirname(os.path.realpath(sys.argv )))
=== setup.py ===
from distutils.core import setup import py2exe setup(console=['foo.py'])
=== results ===
C:\junk\so\py2exe>\python26\python foo.py sys has frozen: False using sys.executable: 'C:\\python26' using sys.argv: 'C:\\junk\\so\\py2exe' # where foo.py lives C:\junk\so\py2exe>dist\foo sys has frozen: True using sys.executable: 'C:\\junk\\so\\py2exe\\dist' using sys.argv: 'C:\\junk\\so\\py2exe\\dist' # where foo.exe lives