简体   繁体   English

python: __file__ 的用法

[英]python: the usage of __file__

When I run当我跑步时

print(__file__)

in Spyder, the absolute location is returned (eg C:\Users\test\test.py).在 Spyder 中,返回绝对位置(例如 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).但是,当我通过 pyinstaller 将它编译成 exe 后运行相同的代码时,只打印 py 文件的名称(只是 test.py)。

How can I fix this?我怎样才能解决这个问题?

In an exe __file__ is not accurate, see this previous answer.在 exe 中__file__不准确,请参阅之前的答案。

In short:简而言之:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM