如何检索模块的路径?

发布于 2024-07-08 18:49:16 字数 90 浏览 9 评论 0原文

我想检测模块是否已更改。 现在,使用 inotify 很简单,您只需要知道要从中获取通知的目录即可。

如何在 python 中检索模块的路径?

I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.

How do I retrieve a module's path in python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

萌辣 2024-07-15 18:49:16
import a_module
print(a_module.__file__)

实际上会给你加载的 .pyc 文件的路径,至少在 Mac OS X 上。所以我想你可以这样做:

import os
path = os.path.abspath(a_module.__file__)

你也可以尝试:

path = os.path.dirname(a_module.__file__)

获取模块的目录。

import a_module
print(a_module.__file__)

Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:

import os
path = os.path.abspath(a_module.__file__)

You can also try:

path = os.path.dirname(a_module.__file__)

To get the module's directory.

单身情人 2024-07-15 18:49:16

python中有inspect模块。

官方文档

检查模块提供了几个有用的函数来帮助获取
有关活动对象的信息,例如模块、类、方法、
函数、回溯、框架对象和代码对象。 例如,
它可以帮助您检查类的内容,检索源代码
方法的代码,提取并格式化函数的参数列表,
或者获取显示详细回溯所需的所有信息。

例子:

>>> import os
>>> import inspect
>>> inspect.getfile(os)
'/usr/lib64/python2.7/os.pyc'
>>> inspect.getfile(inspect)
'/usr/lib64/python2.7/inspect.pyc'
>>> os.path.dirname(inspect.getfile(inspect))
'/usr/lib64/python2.7'

There is inspect module in python.

Official documentation

The inspect module provides several useful functions to help get
information about live objects such as modules, classes, methods,
functions, tracebacks, frame objects, and code objects. For example,
it can help you examine the contents of a class, retrieve the source
code of a method, extract and format the argument list for a function,
or get all the information you need to display a detailed traceback.

Example:

>>> import os
>>> import inspect
>>> inspect.getfile(os)
'/usr/lib64/python2.7/os.pyc'
>>> inspect.getfile(inspect)
'/usr/lib64/python2.7/inspect.pyc'
>>> os.path.dirname(inspect.getfile(inspect))
'/usr/lib64/python2.7'
深巷少女 2024-07-15 18:49:16

正如其他答案所说,最好的方法是使用 __file__ (下面再次演示)。 但是,有一个重要的警告,即如果您单独运行该模块(即作为 __main__),则 __file__ 不存在。

例如,假设您有两个文件(两者都在您的 PYTHONPATH 上):

#/path1/foo.py
import bar
print(bar.__file__)

运行

#/path2/bar.py
import os
print(os.getcwd())
print(__file__)

foo.py 将给出输出:

/path1        # "import bar" causes the line "print(os.getcwd())" to run
/path2/bar.py # then "print(__file__)" runs
/path2/bar.py # then the import statement finishes and "print(bar.__file__)" runs

但是,如果您尝试单独运行 bar.py,您将得到:

/path2                              # "print(os.getcwd())" still works fine
Traceback (most recent call last):  # but __file__ doesn't exist if bar.py is running as main
  File "/path2/bar.py", line 3, in <module>
    print(__file__)
NameError: name '__file__' is not defined 

希望这会有所帮助。 在测试所提供的其他解决方案时,这个警告花费了我大量的时间和困惑。

As the other answers have said, the best way to do this is with __file__ (demonstrated again below). However, there is an important caveat, which is that __file__ does NOT exist if you are running the module on its own (i.e. as __main__).

For example, say you have two files (both of which are on your PYTHONPATH):

#/path1/foo.py
import bar
print(bar.__file__)

and

#/path2/bar.py
import os
print(os.getcwd())
print(__file__)

Running foo.py will give the output:

/path1        # "import bar" causes the line "print(os.getcwd())" to run
/path2/bar.py # then "print(__file__)" runs
/path2/bar.py # then the import statement finishes and "print(bar.__file__)" runs

HOWEVER if you try to run bar.py on its own, you will get:

/path2                              # "print(os.getcwd())" still works fine
Traceback (most recent call last):  # but __file__ doesn't exist if bar.py is running as main
  File "/path2/bar.py", line 3, in <module>
    print(__file__)
NameError: name '__file__' is not defined 

Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.

謸气贵蔟 2024-07-15 18:49:16

我也会尝试解决这个问题的一些变化:

  1. 查找被调用脚本的路径
  2. 查找当前正在执行的脚本的路径
  3. 查找被调用脚本的目录

(其中一些问题已在SO上提出,但已关闭 对于

使用 __file__ 的注意事项

已导入的模块:

import something
something.__file__ 

将返回模块的绝对路径。 但是,给定以下脚本 foo.py:

#foo.py
print '__file__', __file__

使用“python foo.py”调用它将简单地返回“foo.py”。 如果添加 shebang:

#!/usr/bin/python 
#foo.py
print '__file__', __file__

并使用 ./foo.py 调用它,它将返回“./foo.py”。 从不同的目录调用它(例如将 foo.py 放在目录 bar 中),然后调用

python bar/foo.py

或添加 shebang 并直接执行该文件:

bar/foo.py

将返回“bar/foo.py”(相对小路)。

查找目录

现在从那里获取目录,os.path.dirname(__file__) 也可能很棘手。 至少在我的系统上,如果您从与文件相同的目录调用它,它会返回一个空字符串。 前任。

# foo.py
import os
print '__file__ is:', __file__
print 'os.path.dirname(__file__) is:', os.path.dirname(__file__)

将输出:

__file__ is: foo.py
os.path.dirname(__file__) is: 

换句话说,它返回一个空字符串,因此如果您想将它用于当前的文件(而不是文件),这似乎不可靠导入的模块)。 为了解决这个问题,您可以将其包装在对 abspath: 的调用中,

# foo.py
import os
print 'os.path.abspath(__file__) is:', os.path.abspath(__file__)
print 'os.path.dirname(os.path.abspath(__file__)) is:', os.path.dirname(os.path.abspath(__file__))

该调用输出类似以下内容:

os.path.abspath(__file__) is: /home/user/bar/foo.py
os.path.dirname(os.path.abspath(__file__)) is: /home/user/bar

请注意,abspath() 不会解析符号链接。 如果您想这样做,请改用 realpath()。 例如,创建一个指向 file_import_testing.py 的符号链接 file_import_testing_link,内容如下:

import os
print 'abspath(__file__)',os.path.abspath(__file__)
print 'realpath(__file__)',os.path.realpath(__file__)

执行将打印绝对路径,如下所示:

abspath(__file__) /home/user/file_test_link
realpath(__file__) /home/user/file_test.py

file_import_testing_link -> file_import_testing.py

使用检查

@SummerBreeze 提到使用 inspect 模块。

对于导入的模块来说,这似乎工作得很好,而且非常简洁:

import os
import inspect
print 'inspect.getfile(os) is:', inspect.getfile(os)

乖乖地返回绝对路径。 为了查找当前正在执行的脚本的路径:(

inspect.getfile(inspect.currentframe())

感谢@jbochi)

inspect.getabsfile(inspect.currentframe()) 

给出了当前正在执行的脚本的绝对路径(感谢@Sadman_Sakib)。

I will try tackling a few variations on this question as well:

  1. finding the path of the called script
  2. finding the path of the currently executing script
  3. finding the directory of the called script

(Some of these questions have been asked on SO, but have been closed as duplicates and redirected here.)

Caveats of Using __file__

For a module that you have imported:

import something
something.__file__ 

will return the absolute path of the module. However, given the folowing script foo.py:

#foo.py
print '__file__', __file__

Calling it with 'python foo.py' Will return simply 'foo.py'. If you add a shebang:

#!/usr/bin/python 
#foo.py
print '__file__', __file__

and call it using ./foo.py, it will return './foo.py'. Calling it from a different directory, (eg put foo.py in directory bar), then calling either

python bar/foo.py

or adding a shebang and executing the file directly:

bar/foo.py

will return 'bar/foo.py' (the relative path).

Finding the directory

Now going from there to get the directory, os.path.dirname(__file__) can also be tricky. At least on my system, it returns an empty string if you call it from the same directory as the file. ex.

# foo.py
import os
print '__file__ is:', __file__
print 'os.path.dirname(__file__) is:', os.path.dirname(__file__)

will output:

__file__ is: foo.py
os.path.dirname(__file__) is: 

In other words, it returns an empty string, so this does not seem reliable if you want to use it for the current file (as opposed to the file of an imported module). To get around this, you can wrap it in a call to abspath:

# foo.py
import os
print 'os.path.abspath(__file__) is:', os.path.abspath(__file__)
print 'os.path.dirname(os.path.abspath(__file__)) is:', os.path.dirname(os.path.abspath(__file__))

which outputs something like:

os.path.abspath(__file__) is: /home/user/bar/foo.py
os.path.dirname(os.path.abspath(__file__)) is: /home/user/bar

Note that abspath() does NOT resolve symlinks. If you want to do this, use realpath() instead. For example, making a symlink file_import_testing_link pointing to file_import_testing.py, with the following content:

import os
print 'abspath(__file__)',os.path.abspath(__file__)
print 'realpath(__file__)',os.path.realpath(__file__)

executing will print absolute paths something like:

abspath(__file__) /home/user/file_test_link
realpath(__file__) /home/user/file_test.py

file_import_testing_link -> file_import_testing.py

Using inspect

@SummerBreeze mentions using the inspect module.

This seems to work well, and is quite concise, for imported modules:

import os
import inspect
print 'inspect.getfile(os) is:', inspect.getfile(os)

obediently returns the absolute path. For finding the path of the currently executing script:

inspect.getfile(inspect.currentframe())

(thanks @jbochi)

inspect.getabsfile(inspect.currentframe()) 

gives the absolute path of currently executing script (thanks @Sadman_Sakib).

就是爱搞怪 2024-07-15 18:49:16

我不明白为什么没有人谈论这个,但对我来说,最简单的解决方案是使用 imp.find_module("modulename") (文档 此处):

import imp
imp.find_module("os")

它给出了一个元组,其路径位于第二位置:

(<open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540>,
'/usr/lib/python2.7/os.py',
('.py', 'U', 1))

此方法相对于“检查”方法的优点是您不需要导入模块即可使其工作,并且可以在输入中使用字符串。 例如,在检查另一个脚本中调用的模块时很有用。

编辑

在python3中,importlib模块应该这样做:

importlib.util.find_spec的文档:

返回指定模块的规范。

首先,检查 sys.modules 以查看模块是否已导入。 如果是,则返回 sys.modules[name].spec。 如果那恰好是
设置为 None,然后引发 ValueError。 如果模块不在
sys.modules,然后使用 sys.meta_path 搜索合适的规范
给予查找者的“路径”值。 如果没有规范,则不返回任何内容
被发现。

如果名称是子模块(包含点),则父模块是
自动导入。

名称和包参数的工作方式与 importlib.import_module() 相同。
换句话说,相对模块名称(带前导点)有效。

I don't get why no one is talking about this, but to me the simplest solution is using imp.find_module("modulename") (documentation here):

import imp
imp.find_module("os")

It gives a tuple with the path in second position:

(<open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540>,
'/usr/lib/python2.7/os.py',
('.py', 'U', 1))

The advantage of this method over the "inspect" one is that you don't need to import the module to make it work, and you can use a string in input. Useful when checking modules called in another script for example.

EDIT:

In python3, importlib module should do:

Doc of importlib.util.find_spec:

Return the spec for the specified module.

First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].spec is returned. If that happens to be
set to None, then ValueError is raised. If the module is not in
sys.modules, then sys.meta_path is searched for a suitable spec with the
value of 'path' given to the finders. None is returned if no spec could
be found.

If the name is for submodule (contains a dot), the parent module is
automatically imported.

The name and package arguments work the same as importlib.import_module().
In other words, relative module names (with leading dots) work.

世界如花海般美丽 2024-07-15 18:49:16

这是微不足道的。

每个模块都有一个 __file__ 变量,显示其与您现在所在位置的相对路径。

因此,获取模块的目录以通知它很简单:

os.path.dirname(__file__)

This was trivial.

Each module has a __file__ variable that shows its relative path from where you are right now.

Therefore, getting a directory for the module to notify it is simple as:

os.path.dirname(__file__)
静若繁花 2024-07-15 18:49:16
import os
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
import os
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
-小熊_ 2024-07-15 18:49:16
import module
print module.__path__

包还支持一种特殊属性,__path__。 这是
初始化为包含目录名称的列表
在执行该文件中的代码之前,先执行包的 __init__.py
该变量可以修改; 这样做会影响未来的搜索
包中包含的模块和子包。

虽然不经常需要此功能,但它可以用于扩展
在包中找到的一组模块。

来源

import module
print module.__path__

Packages support one more special attribute, __path__. This is
initialized to be a list containing the name of the directory holding
the package’s __init__.py before the code in that file is executed.
This variable can be modified; doing so affects future searches for
modules and subpackages contained in the package.

While this feature is not often needed, it can be used to extend the
set of modules found in a package.

Source

谷夏 2024-07-15 18:49:16

如果您想检索模块路径而不加载

import importlib.util

print(importlib.util.find_spec("requests").origin)

示例输出:

/usr/lib64/python3.9/site-packages/requests/__init__.py

If you want to retrieve the module path without loading it:

import importlib.util

print(importlib.util.find_spec("requests").origin)

Example output:

/usr/lib64/python3.9/site-packages/requests/__init__.py
ぃ弥猫深巷。 2024-07-15 18:49:16

命令行实用程序

您可以将其调整为命令行实用程序,

python-which <package name>

在此处输入图像描述


创建 /usr/local/bin/python-which

#!/usr/bin/env python

import importlib
import os
import sys

args = sys.argv[1:]
if len(args) > 0:
    module = importlib.import_module(args[0])
    print os.path.dirname(module.__file__)

使其可执行

sudo chmod +x /usr/local/bin/python-which

Command Line Utility

You can tweak it to a command line utility,

python-which <package name>

enter image description here


Create /usr/local/bin/python-which

#!/usr/bin/env python

import importlib
import os
import sys

args = sys.argv[1:]
if len(args) > 0:
    module = importlib.import_module(args[0])
    print os.path.dirname(module.__file__)

Make it executable

sudo chmod +x /usr/local/bin/python-which
﹂绝世的画 2024-07-15 18:49:16

你可以只导入你的模块
然后点击它的名字,你就会得到它的完整路径

>>> import os
>>> os
<module 'os' from 'C:\\Users\\Hassan Ashraf\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\os.py'>
>>>

you can just import your module
then hit its name and you'll get its full path

>>> import os
>>> os
<module 'os' from 'C:\\Users\\Hassan Ashraf\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\os.py'>
>>>
止于盛夏 2024-07-15 18:49:16

当您导入模块时,您可以访问大量信息。 查看dir(a_module)。 至于路径,有一个dunder:a_module.__path__。 您也可以只打印模块本身。

>>> import a_module
>>> print(dir(a_module))
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>> print(a_module.__path__)
['/.../.../a_module']
>>> print(a_module)
<module 'a_module' from '/.../.../a_module/__init__.py'>

When you import a module, yo have access to plenty of information. Check out dir(a_module). As for the path, there is a dunder for that: a_module.__path__. You can also just print the module itself.

>>> import a_module
>>> print(dir(a_module))
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>> print(a_module.__path__)
['/.../.../a_module']
>>> print(a_module)
<module 'a_module' from '/.../.../a_module/__init__.py'>
笑饮青盏花 2024-07-15 18:49:16

呃……

>>> import logging
>>> print(logging)
<module 'logging' from 'C:\\Users\\Mike\\AppData\\Local\\Programs\\Python\\Python39\\lib\\logging\\__init__.py'>

Er...

>>> import logging
>>> print(logging)
<module 'logging' from 'C:\\Users\\Mike\\AppData\\Local\\Programs\\Python\\Python39\\lib\\logging\\__init__.py'>
世界和平 2024-07-15 18:49:16

所以我花了相当多的时间尝试用 py2exe 来做到这一点
问题是获取脚本的基本文件夹,无论它是作为 python 脚本还是作为 py2exe 可执行文件运行。 还要让它工作,无论它是从当前文件夹、另一个文件夹还是从系统路径运行(这是最难的)。

最终我使用了这种方法,使用 sys.frozen 作为 py2exe 中运行的指示器:

import os,sys
if hasattr(sys,'frozen'): # only when running in py2exe this exists
    base = sys.prefix
else: # otherwise this is a regular python script
    base = os.path.dirname(os.path.realpath(__file__))

So I spent a fair amount of time trying to do this with py2exe
The problem was to get the base folder of the script whether it was being run as a python script or as a py2exe executable. Also to have it work whether it was being run from the current folder, another folder or (this was the hardest) from the system's path.

Eventually I used this approach, using sys.frozen as an indicator of running in py2exe:

import os,sys
if hasattr(sys,'frozen'): # only when running in py2exe this exists
    base = sys.prefix
else: # otherwise this is a regular python script
    base = os.path.dirname(os.path.realpath(__file__))
倦话 2024-07-15 18:49:16

如果您想从包的任何模块中检索包的根路径,可以使用以下方法(在 Python 3.6 上测试):

from . import __path__ as ROOT_PATH
print(ROOT_PATH)

__init__.py 路径也可以通过使用 __file__ 来引用代码> 代替。

希望这可以帮助!

If you want to retrieve the package's root path from any of its modules, the following works (tested on Python 3.6):

from . import __path__ as ROOT_PATH
print(ROOT_PATH)

The main __init__.py path can also be referenced by using __file__ instead.

Hope this helps!

﹉夏雨初晴づ 2024-07-15 18:49:16

如果您使用 pip 安装它,“pip show”效果很好(“位置”)

$ pip show detectorron2

Name: detectron2
Version: 0.1
Summary: Detectron2 is FAIR next-generation research platform for object detection and segmentation.
Home-page: https://github.com/facebookresearch/detectron2
Author: FAIR
Author-email: None
License: UNKNOWN
Location: /home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages
Requires: yacs, tabulate, tqdm, pydot, tensorboard, Pillow, termcolor, future, cloudpickle, matplotlib, fvcore

更新:

$ python -m pip show mymodule

(作者:wisbucky)

If you installed it using pip, "pip show" works great ('Location')

$ pip show detectron2

Name: detectron2
Version: 0.1
Summary: Detectron2 is FAIR next-generation research platform for object detection and segmentation.
Home-page: https://github.com/facebookresearch/detectron2
Author: FAIR
Author-email: None
License: UNKNOWN
Location: /home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages
Requires: yacs, tabulate, tqdm, pydot, tensorboard, Pillow, termcolor, future, cloudpickle, matplotlib, fvcore

Update:

$ python -m pip show mymodule

(author: wisbucky)

断舍离 2024-07-15 18:49:16

如果您想知道脚本中的绝对路径,可以使用 Path 对象:

from pathlib import Path

print(Path().absolute())
print(Path().resolve('.'))
print(Path().cwd())

cwd() 方法

返回表示当前目录的新路径对象(由 os.getcwd() 返回)

resolve() 方法

使路径成为绝对路径,解析任何符号链接。 返回一个新的路径对象:

If you would like to know absolute path from your script you can use Path object:

from pathlib import Path

print(Path().absolute())
print(Path().resolve('.'))
print(Path().cwd())

cwd() method

Return a new path object representing the current directory (as returned by os.getcwd())

resolve() method

Make the path absolute, resolving any symlinks. A new path object is returned:

森林散布 2024-07-15 18:49:16

如果使用 __file__ 的唯一警告是当当前相对目录为空时(即,当从脚本所在的同一目录作为脚本运行时),那么一个简单的解决方案是:

import os.path
mydir = os.path.dirname(__file__) or '.'
full  = os.path.abspath(mydir)
print __file__, mydir, full

结果:

$ python teste.py 
teste.py . /home/user/work/teste

诀窍在于 dirname() 调用之后的 或 '.' 。 它将 dir 设置为 .,这意味着当前目录,并且是任何与路径相关的函数的有效目录。

因此,并不真正需要使用abspath()。 但如果您无论如何使用它,则不需要这个技巧:abspath() 接受空白路径并将其正确解释为当前目录。

If the only caveat of using __file__ is when current, relative directory is blank (ie, when running as a script from the same directory where the script is), then a trivial solution is:

import os.path
mydir = os.path.dirname(__file__) or '.'
full  = os.path.abspath(mydir)
print __file__, mydir, full

And the result:

$ python teste.py 
teste.py . /home/user/work/teste

The trick is in or '.' after the dirname() call. It sets the dir as ., which means current directory and is a valid directory for any path-related function.

Thus, using abspath() is not truly needed. But if you use it anyway, the trick is not needed: abspath() accepts blank paths and properly interprets it as the current directory.

╄→承喏 2024-07-15 18:49:16

我想贡献一个常见的场景(在 Python 3 中)并探索一些实现它的方法。

内置函数 open() 接受相对或绝对路径作为它的第一个参数。 不过,相对路径被视为相对于当前工作目录,因此建议将绝对路径传递给文件。

简单地说,如果您运行包含以下代码的脚本文件,则保证会在脚本文件所在的同一目录中创建 example.txt 文件located:

with open('example.txt', 'w'):
    pass

要修复此代码,我们需要获取脚本的路径并将其设置为绝对路径。 为了确保路径是绝对的,我们只需使用 os .path.realpath() 函数。 要获取脚本的路径,有几个返回各种路径结果的常用函数:

  • os.getcwd()
  • os.path.realpath('example.txt')
  • < code>sys.argv[0]
  • __file__

两个函数 os.getcwd()os.path.realpath() 根据当前工作目录返回路径结果。 一般不是我们想要的。 sys.argv 列表的第一个元素是 < em>根脚本的路径(您运行的脚本),无论您是在根脚本本身还是在其任何模块中调用该列表。 在某些情况下它可能会派上用场。 __file__ 变量包含调用它的模块的路径。


以下代码在脚本所在的同一目录中正确创建文件 example.txt

filedir = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(filedir, 'example.txt')

with open(filepath, 'w'):
    pass

I'd like to contribute with one common scenario (in Python 3) and explore a few approaches to it.

The built-in function open() accepts either relative or absolute path as its first argument. The relative path is treated as relative to the current working directory though so it is recommended to pass the absolute path to the file.

Simply said, if you run a script file with the following code, it is not guaranteed that the example.txt file will be created in the same directory where the script file is located:

with open('example.txt', 'w'):
    pass

To fix this code we need to get the path to the script and make it absolute. To ensure the path to be absolute we simply use the os.path.realpath() function. To get the path to the script there are several common functions that return various path results:

  • os.getcwd()
  • os.path.realpath('example.txt')
  • sys.argv[0]
  • __file__

Both functions os.getcwd() and os.path.realpath() return path results based on the current working directory. Generally not what we want. The first element of the sys.argv list is the path of the root script (the script you run) regardless of whether you call the list in the root script itself or in any of its modules. It might come handy in some situations. The __file__ variable contains path of the module from which it has been called.


The following code correctly creates a file example.txt in the same directory where the script is located:

filedir = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(filedir, 'example.txt')

with open(filepath, 'w'):
    pass
记忆で 2024-07-15 18:49:16

这个问题的现代(Python >= 3.7)解决方案是 importlib.resources.files()

from importlib import resources
resources.files(package_name)
# => WindowsPath("C:\Path\to\your\package\")

A modern (Python >= 3.7) solution to this problem is importlib.resources.files()

from importlib import resources
resources.files(package_name)
# => WindowsPath("C:\Path\to\your\package\")
心碎的声音 2024-07-15 18:49:16

在 python 包的模块中,我必须引用与 package.json 位于同一目录中的文件。 前任。

some_dir/
  maincli.py
  top_package/
    __init__.py
    level_one_a/
      __init__.py
      my_lib_a.py
      level_two/
        __init__.py
        hello_world.py
    level_one_b/
      __init__.py
      my_lib_b.py

因此,在上面我必须从 my_lib_a.py 模块调用 maincli.py ,因为知道 top_package 和 maincli.py 位于同一目录中。 以下是我获取 maincli.py 路径的方法:

import sys
import os
import imp


class ConfigurationException(Exception):
    pass


# inside of my_lib_a.py
def get_maincli_path():
    maincli_path = os.path.abspath(imp.find_module('maincli')[1])
    # top_package = __package__.split('.')[0]
    # mod = sys.modules.get(top_package)
    # modfile = mod.__file__
    # pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))
    # maincli_path = os.path.join(pkg_in_dir, 'maincli.py')

    if not os.path.exists(maincli_path):
        err_msg = 'This script expects that "maincli.py" be installed to the '\
        'same directory: "{0}"'.format(maincli_path)
        raise ConfigurationException(err_msg)

    return maincli_path

根据 PlasmaBinturong 的发布,我修改了代码。

From within modules of a python package I had to refer to a file that resided in the same directory as package. Ex.

some_dir/
  maincli.py
  top_package/
    __init__.py
    level_one_a/
      __init__.py
      my_lib_a.py
      level_two/
        __init__.py
        hello_world.py
    level_one_b/
      __init__.py
      my_lib_b.py

So in above I had to call maincli.py from my_lib_a.py module knowing that top_package and maincli.py are in the same directory. Here's how I get the path to maincli.py:

import sys
import os
import imp


class ConfigurationException(Exception):
    pass


# inside of my_lib_a.py
def get_maincli_path():
    maincli_path = os.path.abspath(imp.find_module('maincli')[1])
    # top_package = __package__.split('.')[0]
    # mod = sys.modules.get(top_package)
    # modfile = mod.__file__
    # pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))
    # maincli_path = os.path.join(pkg_in_dir, 'maincli.py')

    if not os.path.exists(maincli_path):
        err_msg = 'This script expects that "maincli.py" be installed to the '\
        'same directory: "{0}"'.format(maincli_path)
        raise ConfigurationException(err_msg)

    return maincli_path

Based on posting by PlasmaBinturong I modified the code.

梦忆晨望 2024-07-15 18:49:16

如果您希望在“程序”中动态执行此操作,请尝试以下代码:
我的观点是,您可能不知道要对其进行“硬编码”的模块的确切名称。
它可以从列表中选择,也可以当前未运行以使用 __file__。

(我知道,它在 Python 3 中不起作用)

global modpath
modname = 'os' #This can be any module name on the fly
#Create a file called "modname.py"
f=open("modname.py","w")
f.write("import "+modname+"\n")
f.write("modpath = "+modname+"\n")
f.close()
#Call the file with execfile()
execfile('modname.py')
print modpath
<module 'os' from 'C:\Python27\lib\os.pyc'>

我试图摆脱“全局”问题,但发现它不起作用的情况
我认为“execfile()”可以在Python 3中模拟
由于这是在程序中,因此可以轻松地将其放入方法或模块中以供重用。

If you wish to do this dynamically in a "program" try this code:
My point is, you may not know the exact name of the module to "hardcode" it.
It may be selected from a list or may not be currently running to use __file__.

(I know, it will not work in Python 3)

global modpath
modname = 'os' #This can be any module name on the fly
#Create a file called "modname.py"
f=open("modname.py","w")
f.write("import "+modname+"\n")
f.write("modpath = "+modname+"\n")
f.close()
#Call the file with execfile()
execfile('modname.py')
print modpath
<module 'os' from 'C:\Python27\lib\os.pyc'>

I tried to get rid of the "global" issue but found cases where it did not work
I think "execfile()" can be emulated in Python 3
Since this is in a program, it can easily be put in a method or module for reuse.

死开点丶别碍眼 2024-07-15 18:49:16

这是一个快速的 bash 脚本,以防它对任何人有用。 我只是希望能够设置一个环境变量,以便我可以 pushd 到代码。

#!/bin/bash
module=${1:?"I need a module name"}

python << EOI
import $module
import os
print os.path.dirname($module.__file__)
EOI

外壳示例:

[root@sri-4625-0004 ~]# export LXML=$(get_python_path.sh lxml)
[root@sri-4625-0004 ~]# echo $LXML
/usr/lib64/python2.7/site-packages/lxml
[root@sri-4625-0004 ~]#

Here is a quick bash script in case it's useful to anyone. I just want to be able to set an environment variable so that I can pushd to the code.

#!/bin/bash
module=${1:?"I need a module name"}

python << EOI
import $module
import os
print os.path.dirname($module.__file__)
EOI

Shell example:

[root@sri-4625-0004 ~]# export LXML=$(get_python_path.sh lxml)
[root@sri-4625-0004 ~]# echo $LXML
/usr/lib64/python2.7/site-packages/lxml
[root@sri-4625-0004 ~]#
优雅的叶子 2024-07-15 18:49:16

如果您使用 pip,则可以调用 pip show,但必须使用您正在使用的特定版本的 python 来调用它。 例如,这些都可能给出不同的结果:

$ python -m pip show numpy
$ python2.7 -m pip show numpy
$ python3 -m pip show numpy

Location: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python

不要简单地运行 $ pip show numpy,因为不能保证不同的 pip 是相同的。 >python 版本正在调用。

If you used pip, then you can call pip show, but you must call it using the specific version of python that you are using. For example, these could all give different results:

$ python -m pip show numpy
$ python2.7 -m pip show numpy
$ python3 -m pip show numpy

Location: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python

Don't simply run $ pip show numpy, because there is no guarantee that it will be the same pip that different python versions are calling.

○闲身 2024-07-15 18:49:16

如果您的导入是一个站点包(例如pandas),我建议使用此方法来获取其目录(如果导入是一个模块,则不起作用,例如pathlib):

from importlib import resources  # part of core Python
import pandas as pd

package_dir = resources.path(package=pd, resource="").__enter__()

一般情况当任务是关于访问站点包的路径/资源。

If your import is a site-package (e.g. pandas) I recommend this to get its directory (does not work if import is a module, like e.g. pathlib):

from importlib import resources  # part of core Python
import pandas as pd

package_dir = resources.path(package=pd, resource="").__enter__()

In general importlib.resources can be considered when a task is about accessing paths/resources of a site package.

季末如歌 2024-07-15 18:49:16

这里我正在打印cProfile包路径:-

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

Here im printing cProfile package path:-

import cProfile
import os
path = os.path.abspath(cProfile.__file__)
print(path)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文