获取 .py 源文件的位置 [英] Get location of the .py source file

查看:69
本文介绍了获取 .py 源文件的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在目录 e 中有一个 python 文件,如下所示:

Say I have a python file in directory e like this:

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

在目录 e 下我有几个我想访问的文件夹,但如果从其他任何地方而不是从文件夹 e 执行 file.py,则相对路径不会为我工作.此外,文件夹 e 可以位于任何地方,但始终带有一组子文件夹,因此绝对路径不起作用.

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. Also folder e could be located anywhere but always with the a set of sub folders so absolute path will not work.

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

First, is there any function to get the absolute path in relation to the source files location?

如果没有,任何想法如何解决这个问题?把用到的命令行抓起来,把CWD加在一起?

If not, any ideas how to sort this out? Grab the command line used and add the CWD together?

我的问题是这个文件夹被安装在 20 台不同的机器和操作系统上,我希望它尽可能动态,几乎没有配置和必须安装的规则"等.

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.

推荐答案

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

这篇关于获取 .py 源文件的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆