Python: 难以获取脚本的当前路径

Python: Having difficulty obtaining current path of script

我对编程和 Python 都很陌生。我正在 Mac OSX,尝试使用 PyCharm。我看过 this, this, this,还有 几个

但我似乎无法获取当前 运行 文件的路径。如果我使用 os.getcwd(),我会得到

'/Users/AlanH/Python'

当真的,完整的文件路径是:

'/Users/AlanH/Python/Exercises/PythonBasics/starthere.py'

所以我不明白为什么这不起作用。

如果我尝试使用 sys.path[0],它会弹出一条路径,将我带到我的图书馆,然后进入 Enthought(不知道为什么,即使我使用的是 Anaconda 发行版)。

我可以继续讨论我尝试过的所有可能的解决方案,但没有任何效果。我想要的只是获取当前 运行 文件的确切路径。所以要么

'/Users/AlanH/Python/Exercises/PythonBasics/starthere.py'

或这个

'/Users/AlanH/Python/Exercises/PythonBasics'

会做。

有人可以帮忙吗?

import os
print(os.path.abspath(__file__))

本地测试结果如下:

eb@cube ~/Share $ python Whosebug/path.py
/home/eb/Share/Whosebug/path.py