How do I find the location of Python module source

2019-01-01 16:23发布

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.

标签: python module
16条回答
余欢
2楼-- · 2019-01-01 17:01

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

查看更多
高级女魔头
3楼-- · 2019-01-01 17:01

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))
查看更多
闭嘴吧你
4楼-- · 2019-01-01 17:01

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.

查看更多
伤终究还是伤i
5楼-- · 2019-01-01 17:04

You can see source right from the git repository. For example here is the datetime module and as a bonus, the subprocess module.

If you do more digging around you can find the traditional implementation of the standard Python interpreter, which is written in ‘C’ and also called ‘CPython’

查看更多
春风洒进眼中
6楼-- · 2019-01-01 17:06

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

查看更多
深知你不懂我心
7楼-- · 2019-01-01 17:08

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

查看更多
登录 后发表回答