我如何了解一个给定的Python模块的源文件安装在哪里?Windows上的方法和Linux上的方法不同吗?
我特别试图寻找datetime模块的源代码,但我对更一般的答案也感兴趣。
我如何了解一个给定的Python模块的源文件安装在哪里?Windows上的方法和Linux上的方法不同吗?
我特别试图寻找datetime模块的源代码,但我对更一般的答案也感兴趣。
当前回答
如果你没有使用解释器,那么你可以运行下面的代码:
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
其他回答
从命令行运行python -v应该会告诉你导入了什么以及从哪里导入。这在Windows和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
...
我不知道我安装的那些不好的时光网是什么!
只是更新答案,以防现在有人需要它,我在Python 3.9和使用Pip来管理包。就用pip show,例如:
pip show numpy
它将为您提供所有详细信息,包括pip存储所有其他包的位置。
sys。Path list包含在运行时搜索模块的目录列表:
python -v
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]
看看这个漂亮的"cdp"命令,cd到包含指定Python模块源代码的目录:
cdp () {
cd "$(python -c "import os.path as _, ${1}; \
print _.dirname(_.realpath(${1}.__file__[:-1]))"
)"
}
我意识到这个答案晚了4年,但现有的答案在误导人们。
正确的方法是永远不要__file__,或者尝试遍历sys. file__。路径和搜索自己,等等(除非你需要向后兼容超过2.1)。
它是inspect模块——特别是getfile或getsourcefile。
除非你想学习和实现CPython 2的规则(这些规则有文档,但很痛苦)。3.x)用于将.pyc映射到.py文件;处理.zip档案、eggs和模块包;尝试不同的方法得到。so/的路径。不支持__file__的Pyd文件;弄清楚Jython/IronPython/PyPy做什么;等。在这种情况下,放手去做吧。
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.