Reputation: 1
I am mainly trying to get examples from the library of the base functions to help aid me in my studies of Python. I am running Linux Mint 17 and I would like to simply know the path to the base functions, so I can open them and view the Python code they contain.
Upvotes: 0
Views: 148
Reputation: 481
Each non built-ins modules have a __file__
attribute. He contains the fullpath of the loaded file, so if it's a module write in python, you will get a '.pyc' file, if it's a C module a '.so'.
>>> import collections # from the std lib in pure python
>>> collections.__file__
'/usr/lib/python2.7/collections.pyc'
>>> import datetime # from the std lib as a C module
>>> datetime.__file__
'/usr/lib/python2.7/lib-dynload/datetime.so'
>>> import itertools # from the std lib but a built-in module
>>> itertools.__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
You can also use the inspect module, who have a .getsourcefile
function, this work not only at module level but a function level too. If the function is declared in python !
>>> import inspect
>>> inspect.getsourcefile(collections) # Pure python
'/usr/lib/python2.7/collections.py'
>>> inspect.getsourcefile(collections.namedtuple) # Work with a function too.
'/usr/lib/python2.7/collections.py'
>>> inspect.getsourcefile(datetime) # C module so it will return just None
>>> inspect.getsourcefile(itertools) # Built-in so it raise an exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/inspect.py", line 444, in getsourcefile
filename = getfile(object)
File "/usr/lib/python2.7/inspect.py", line 403, in getfile
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module 'itertools' (built-in)> is a built-in module
Has you can see, if it's a external C library, .getsourcefile
return nothing. And if it's a built-in module/function/class, it raise a TypeError
exception.
The others advantages of .getsourcefile
over __file__
is that if the function/class is declared in a subfile of the module it return the right file. And you can even use it on the type of a "an unknown" object and do inspect.getsourcefile(type(obj))
.
(It's test if the source file exist too and return None
if the '.pyc' is loaded but the '.py' doesn't exist)
Upvotes: 2
Reputation: 12158
The base install is usually in /usr/lib{,64}/python*/
, and installed packages in /usr/lib{,64}/python*/site-packages
:
ch3ka@x200 /tmp % locate this.py | grep python3\.4
/usr/lib64/python3.4/this.py
(this is the path to the module this
- substitute 3\.4
with your python version, or simply skip the | grep
)
But when using virtualenv, your PYTHONPATH may be anywhere, depends on what you specified when creating the virtualenvs. Use locate(1)
and your judgement.
Upvotes: 0