简体   繁体   English

获取 .py 源文件的位置

[英]Get location of the .py source file

Say I have a python file in directory e like this:假设我在目录e 中有一个 python 文件,如下所示:

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

Under directory e I have a few folders I want to access but if file.py is executed from anywhere else rather than from folder e the relative path won't work for me.在目录e 下,我有几个要访问的文件夹,但是如果从其他任何地方而不是从文件夹e执行 file.py,则相对路径对我不起作用。 Also folder e could be located anywhere but always with the a set of sub folders so absolute path will not work.此外,文件夹e可以位于任何地方,但始终带有一组子文件夹,因此绝对路径不起作用。

First, is there any function to get the absolute path in relation to the source files location?首先,是否有任何函数可以获取与源文件位置相关的绝对路径?

If not, any ideas how to sort this out?如果没有,任何想法如何解决这个问题? Grab the command line used and add the CWD together?抓取使用的命令行并将 CWD 添加到一起?

My problem here is that this folder are being installed on 20 different machines and OS's and I want it to be as dynamic as possible with little configurations and "rules" where it has to be installed etc.我的问题是这个文件夹被安装在 20 台不同的机器和操作系统上,我希望它尽可能动态,几乎没有配置和必须安装的“规则”等。

# 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.这是我的解决方案,它 (a) 获取 .py 文件而不是 .pyc 文件,并且 (b) 整理符号链接。

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.在 Linux 上工作时, .py文件通常被符号链接到另一个地方,而.pyc文件是在符号链接的 py 文件旁边的目录中生成的。 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:在 Python +3.4 中使用pathlib更方便:

from pathlib import Path

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

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

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