问题:如何找到Python模块源的位置?

如何了解给定Python模块的源文件的安装位置?Windows和Linux上的方法是否不同?

我正在寻找来源 datetime模块,但我也对更通用的答案感兴趣。

How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?

I’m trying to look for the source of the datetime module in particular, but I’m interested in a more general answer as well.


回答 0

对于纯python模块,您可以通过查看来找到源themodule.__file__。但是,datetime模块是用C编写的,因此datetime.__file__指向.so文件(datetime.__file__在Windows中没有),因此看不到源代码。

如果您下载python源tarball并将其解压缩,则可以在模块中找到模块的代码子目录中。

例如,如果要查找python 2.6的日期时间代码,可以查看

Python-2.6/Modules/datetimemodule.c

您也可以在以下网址找到最新的Mercurial版本: https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c

For a pure python module you can find the source by looking at themodule.__file__. The datetime module, however, is written in C, and therefore datetime.__file__ points to a .so file (there is no datetime.__file__ on Windows), and therefore, you can’t see the source.

If you download a python source tarball and extract it, the modules’ code can be found in the Modules subdirectory.

For example, if you want to find the datetime code for python 2.6, you can look at

Python-2.6/Modules/datetimemodule.c

You can also find the latest Mercurial version on the web at https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c


回答 1

python -v从命令行运行应该告诉您正在导入什么以及从何处导入。这适用于Windows和Mac OSX。

C:\>python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# C:\Python24\lib\site.pyc has bad mtime
import site # from C:\Python24\lib\site.py
# wrote C:\Python24\lib\site.pyc
# C:\Python24\lib\os.pyc has bad mtime
import os # from C:\Python24\lib\os.py
# wrote C:\Python24\lib\os.pyc
import nt # builtin
# C:\Python24\lib\ntpath.pyc has bad mtime
...

我不确定那些不好的mtime在我的装置上!

Running python -v from the command line should tell you what is being imported and from where. This works for me on Windows and Mac OS X.

C:\>python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# C:\Python24\lib\site.pyc has bad mtime
import site # from C:\Python24\lib\site.py
# wrote C:\Python24\lib\site.pyc
# C:\Python24\lib\os.pyc has bad mtime
import os # from C:\Python24\lib\os.py
# wrote C:\Python24\lib\os.pyc
import nt # builtin
# C:\Python24\lib\ntpath.pyc has bad mtime
...

I’m not sure what those bad mtime’s are on my install!


回答 2

我知道这个答案要晚4年了,但是现有的答案会误导人们。

做到这一点的正确方法永远不会__file__,或者尝试逐步完成sys.path搜索并寻找自己,等等(除非您需要向后兼容2.1以上)。

这是模块特别getfilegetsourcefile

除非您想学习和实现用于映射.pyc.py文件的规则(对于CPython 2.x,已记录但很痛苦,而对于其他实现或3.x则没有任何记录);处理.zip归档文件,鸡蛋和模块包;尝试不同的方法以获取.so/.pyd不支持的文件__file__ ; 弄清楚Jython / IronPython / PyPy的作用;等。在这种情况下,请继续努力。

同时,每个Python版本的2.0 或更高版本的源均可在线获得http://hg.python.org/cpython/file/X.Y/(例如2.73.3)。因此,一旦发现inspect.getfile(datetime).so或之类的.pyd文件/usr/local/lib/python2.7/lib-dynload/datetime.so,就可以在Modules目录中查找它。严格来说,无法确定哪个文件定义了哪个模块,但是几乎所有文件都不是foo.cfoomodule.c,因此不难猜测datetimemodule.c是您想要的。

I realize this answer is 4 years late, but the existing answers are misleading people.

The right way to do this is never __file__, or trying to walk through sys.path and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).

It’s the module—in particular, getfile or getsourcefile.

Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping .pyc to .py files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to .so/.pyd files that don’t support __file__; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it.

Meanwhile, every Python version’s source from 2.0+ is available online at http://hg.python.org/cpython/file/X.Y/ (e.g., 2.7 or 3.3). So, once you discover that inspect.getfile(datetime) is a .so or .pyd file like /usr/local/lib/python2.7/lib-dynload/datetime.so, you can look it up inside the Modules directory. Strictly speaking, there’s no way to be sure of which file defines which module, but nearly all of them are either foo.c or foomodule.c, so it shouldn’t be hard to guess that datetimemodule.c is what you want.


回答 3

sys.path列表包含将在运行时搜索模块的目录列表:

python -v
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]

The sys.path list contains the list of directories which will be searched for modules at runtime:

python -v
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]

回答 4

如果您使用pip安装模块,则仅pip show $module返回位置。

If you’re using pip to install your modules, just pip show $module the location is returned.


回答 5

从标准库尝试imp.find_module

>>> import imp
>>> imp.find_module('fontTools')
(None, 'C:\\Python27\\lib\\site-packages\\FontTools\\fontTools', ('', '', 5))
>>> imp.find_module('datetime')
(None, 'datetime', ('', '', 6))

from the standard library try imp.find_module

>>> import imp
>>> imp.find_module('fontTools')
(None, 'C:\\Python27\\lib\\site-packages\\FontTools\\fontTools', ('', '', 5))
>>> imp.find_module('datetime')
(None, 'datetime', ('', '', 6))

回答 6

datetime 是一个内置模块,因此没有(Python)源文件。

对于来自.py(或.pyc)文件的模块,可以使用mymodule.__file__,例如

> import random
> random.__file__
'C:\\Python25\\lib\\random.pyc'

datetime is a builtin module, so there is no (Python) source file.

For modules coming from .py (or .pyc) files, you can use mymodule.__file__, e.g.

> import random
> random.__file__
'C:\\Python25\\lib\\random.pyc'

回答 7

在python解释器中,您可以导入特定的模块,然后键入help(module)。这给出了详细信息,例如名称,文件,模块文档,描述等。

例如:

import os

help(os)


Help on module os:

NAME

os - OS routines for Mac, NT, or Posix depending on what system we're on.

FILE

/usr/lib/python2.6/os.py

MODULE DOCS

http://docs.python.org/library/os

DESCRIPTION

This exports:

- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.

- os.path is one of the modules posixpath, or ntpath

- os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'

In the python interpreter you could import the particular module and then type help(module). This gives details such as Name, File, Module Docs, Description et al.

Ex:

import os

help(os)


Help on module os:

NAME

os - OS routines for Mac, NT, or Posix depending on what system we're on.

FILE

/usr/lib/python2.6/os.py

MODULE DOCS

http://docs.python.org/library/os

DESCRIPTION

This exports:

- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.

- os.path is one of the modules posixpath, or ntpath

- os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'

et al


回答 8

这是获取模块文件名的一种方法,适用于shell别名:

echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)'  | python - 

设置为别名:

alias getpmpath="echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)'  | python - "

使用方法:

$ getpmpath twisted
/usr/lib64/python2.6/site-packages/twisted/__init__.pyc
$ getpmpath twisted.web
/usr/lib64/python2.6/site-packages/twisted/web/__init__.pyc

Here’s a one-liner to get the filename for a module, suitable for shell aliasing:

echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)'  | python - 

Set up as an alias:

alias getpmpath="echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)'  | python - "

To use:

$ getpmpath twisted
/usr/lib64/python2.6/site-packages/twisted/__init__.pyc
$ getpmpath twisted.web
/usr/lib64/python2.6/site-packages/twisted/web/__init__.pyc

回答 9

Python 3.2中的新功能,您现在可以code_info()在dis模块中使用例如:http : //docs.python.org/dev/whatsnew/3.2.html#dis

New in Python 3.2, you can now use e.g. code_info() from the dis module: http://docs.python.org/dev/whatsnew/3.2.html#dis


回答 10

出这个漂亮的“ cdp”命令以cd到包含指示的Python模块源的目录:

cdp () {
  cd "$(python -c "import os.path as _, ${1}; \
    print _.dirname(_.realpath(${1}.__file__[:-1]))"
  )"
}

Check out this nifty “cdp” command to cd to the directory containing the source for the indicated Python module:

cdp () {
  cd "$(python -c "import os.path as _, ${1}; \
    print _.dirname(_.realpath(${1}.__file__[:-1]))"
  )"
}

回答 11

在Windows上,您可以找到python模块的位置,如下所示:ie find rest_framework模块 在此处输入图片说明

On windows you can find the location of the python module as shown below:i.e find rest_framework module enter image description here


回答 12

在Ubuntu 12.04上,例如可以在以下位置找到python2的numpy软件包:

/usr/lib/python2.7/dist-packages/numpy

当然,这不是通用答案

On Ubuntu 12.04, for example numpy package for python2, can be found at:

/usr/lib/python2.7/dist-packages/numpy

Of course, this is not generic answer


回答 13

并非所有的python模块都是用python编写的。日期时间恰好是其中之一,并且(在Linux上)是datetime.so。

您必须将源代码下载到python标准库中才能使用它。

Not all python modules are written in python. Datetime happens to be one of them that is not, and (on linux) is datetime.so.

You would have to download the source code to the python standard library to get at it.


回答 14

对于那些喜欢GUI解决方案的用户:如果使用的是GUI,例如Spyder(Anaconda安装的一部分),则可以右键单击模块名称(例如“ import csv”中的“ csv”),然后选择“ go定义”-这将打开文件,但在顶部您也可以看到确切的文件位置(“ C:…. csv.py”)

For those who prefer a GUI solution: if you’re using a gui such as Spyder (part of the Anaconda installation) you can just right-click the module name (such as “csv” in “import csv”) and select “go to definition” – this will open the file, but also on the top you can see the exact file location (“C:….csv.py”)


回答 15

如果您不使用解释器,则可以运行以下代码:

import site
print (site.getsitepackages())

输出:

['C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']

Array中的第二个元素将是您的包裹位置。在这种情况下:

C:\Users\<your username>\AppData\Local\Programs\Python\Python37\lib\site-packages

If you are not using interpreter then you can run the code below:

import site
print (site.getsitepackages())

Output:

['C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']

The second element in Array will be your package location. In this case:

C:\Users\<your username>\AppData\Local\Programs\Python\Python37\lib\site-packages

回答 16

从终端检查是否已安装多个python版本的另一种方法。

-MBP:〜python3 -m pip显示pyperclip

位置:/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-

MBP:〜python -m pip show pyperclip

位置:/Users/umeshvuyyuru/Library/Python/2.7/lib/python/site-packages

Another way to check if you have multiple python versions installed, from the terminal.

-MBP:~python3 -m pip show pyperclip

Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-

MBP:~ python -m pip show pyperclip

Location: /Users/umeshvuyyuru/Library/Python/2.7/lib/python/site-packages


回答 17

在Spyder之类的IDE中,导入模块,然后分别运行该模块。 在此处输入图片说明

In an IDE like Spyder, import the module and then run the module individually. enter image description here


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。