Likes_to_Program123
Likes_to_Program123

Reputation: 47

python: the usage of __file__

When I run

print(__file__)

in Spyder, the absolute location is returned (e.g. C:\Users\test\test.py).

However, when I run the same code after I compiled it into an exe via pyinstaller, only the name of the py file is printed (just test.py).

How can I fix this?

Upvotes: 0

Views: 158

Answers (1)

Cirrith
Cirrith

Reputation: 82

In an exe __file__ is not accurate, see this previous answer.

In short:

import sys
if getattr(sys, 'frozen', False):
    # Pyinstaller exe
    location = sys.executable
else:
    # Running directly python
    location = __file__

Upvotes: 1

Related Questions