获取. py 源文件的位置

假设我在目录 你好中有一个如下的 python 文件:

/a/b/c/d/e/file.py

在目录 你好下,我有几个想要访问的文件夹,但是如果 file.py 是从其他地方而不是从文件夹 你好执行的,那么相对路径对我来说就不起作用了。文件夹 你好也可以位于任何地方,但总是与一组子文件夹,所以绝对路径不会工作。

首先,是否有函数来获取与源文件位置相关的绝对路径?

如果没有,有什么办法可以解决这个问题吗? 抓住命令行并将 CWD 添加到一起?

我在这里的问题是,这个文件夹是安装在20个不同的机器和操作系统,我希望它是动态的,尽可能少的配置和“规则”,它必须安装等。

59341 次浏览
# in /a/b/c/d/e/file.py
import os
os.path.dirname(os.path.abspath(__file__)) # /a/b/c/d/e

Here is my solution which (a) gets the .py file rather than the .pyc file, and (b) sorts out symlinks.

Working on Linux, the .py files are often symlinked to another place, and the .pyc files are generated in the directory next to the symlinked py files. To find the real path of the source file, here's part of a script that I use to find the source path.

try:
modpath = module.__file__
except AttributeError:
sys.exit('Module does not have __file__ defined.')
# It's a script for me, you probably won't want to wrap it in try..except


# Turn pyc files into py files if we can
if modpath.endswith('.pyc') and os.path.exists(modpath[:-1]):
modpath = modpath[:-1]


# Sort out symlinks
modpath = os.path.realpath(modpath)

In Python +3.4 use of pathlib is more handy:

from pathlib import Path


source_path = Path(__file__).resolve()
source_dir = source_path.parent