0

I apparently have multiple versions of a module installed and I am trying to figure out where the files are because only one of them is from package management and I want to delete the other.

Is there a simple way to ask Python where it found a module after importing it?

Sarien
  • 6,647
  • 6
  • 35
  • 55

2 Answers2

3

if the module isn't built-in, you can do this:

import your_module
print(your_module.__file__)

test:

>>> import os
>>> print(os.__file__)
L:\Python34\lib\os.py

if module is built-in, you get an error:

>>> import sys
>>> print(sys.__file__)
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
>>> 

(check if module has the __file__ attribute using hasattr is also an option to avoid errors; if hasattr(module_name, '__file__'):)

also: by directly printing the module:

>>> print(os)
<module 'os' from 'L:\\Python34\\lib\\os.py'>
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

You can use __file__ after importing the module:

>>> import os 
>>> os.__file__
'/usr/lib/python2.7/os.pyc'
bhansa
  • 7,282
  • 3
  • 30
  • 55