PDA

View Full Version : Python: Getting file name.



Sailor5
November 24th, 2010, 09:41 PM
Ahoy Sailor!

So I've compiled my Python script using Py2Exe. Now I'm facing a dilemma, getting the file name of itself ( the file I compiled ).

I've used two different commands to get the name. However they both have issues.

print sys.argv[0]This works fine and dandy. If you execute the script via console. If you execute it via double clicking. It won't hold the name.


nme = inspect.currentframe().f_code.co_filenameThis comes back with the original source file name. So after we've built an executable from SOURCE.py to get EXECUTABLE.exe and use this method. It will come back with SOURCE.py not the executable name which we want.

What other methods are there?

Thanks Bye!

DaithiF
November 24th, 2010, 10:57 PM
import os, sys

if __name__ == '__main__':
print 'Hello world'
if hasattr(sys,"frozen") and sys.frozen in ("windows_exe", "console_exe"):
path = (os.path.abspath(sys.executable))
else:
path = os.path.abspath(__file__)
print 'hello from %s' % path

Sailor5
November 26th, 2010, 02:03 PM
import os, sys

if __name__ == '__main__':
print 'Hello world'
if hasattr(sys,"frozen") and sys.frozen in ("windows_exe", "console_exe"):
path = (os.path.abspath(sys.executable))
else:
path = os.path.abspath(__file__)
print 'hello from %s' % path



Hello world
Traceback (most recent call last):
File "Python.py", line 25, in ?
NameError: name '__file__' is not defined

DaithiF
November 26th, 2010, 02:10 PM
what is sys.frozen when you execute it as an .exe?

Sailor5
November 26th, 2010, 02:17 PM
what is sys.frozen when you execute it as an .exe?
it comes back with
AttributeError: 'str' object has no attribute 'frozen'

DaithiF
November 26th, 2010, 02:48 PM
hmm, can you check you code carefully for typos -- that error indicates you've asked for the frozen attribute of some string object, but i'm asking you what the frozen attribute of the sys module is.

Sailor5
November 26th, 2010, 06:59 PM
hmm, can you check you code carefully for typos -- that error indicates you've asked for the frozen attribute of some string object, but i'm asking you what the frozen attribute of the sys module is.
Oops I'd defined a variable named sys (Doh!) printing sys.executable gets me the file name. Thanks a lot!