How do I learn where the source file for a given Python module is installed? (Is the method is different on Windows than Linux?)
(I want to look at the datetime module sources, but I thought I'd ask a more general question.)
How do I learn where the source file for a given Python module is installed? (Is the method is different on Windows than Linux?)
(I want to look at the datetime module sources, but I thought I'd ask a more general question.)
The sys.path
list contains the list of directories which will be searched for modules at runtime:
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]
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!
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'
Not all python modules are written in python. Datetime happens to be one of them, and (on linux) is datetime.so.
You would have to download the source code to the python standard library to get at it.
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 svn version on the web at http://svn.python.org/projects/python/trunk/Modules/datetimemodule.c
Check out this nifty "cdp" command to cd to the directory containing the source for the indicated Python module: http://chris-lamb.co.uk/2010/04/22/locating-source-any-python-module/