4

Im sure there is a simple way to get a modules path from the modulename, right? I.e. I want to retrieve /path/to/module from path.to.module preferably in python 2.7.

I dont intend to import the module and I have the modulename as a string.

joidegn
  • 1,078
  • 9
  • 19
  • Does this post/answer address your question? http://stackoverflow.com/questions/247770/retrieving-python-module-path – Kyss Tao Mar 02 '12 at 14:12
  • 1
    I should have been more clear in my question, I dont intend to import the module. The post thus doesnt help and I have read it before. – joidegn Mar 02 '12 at 14:19

3 Answers3

10

This is fairly easy after importing a module:

import os
print os.__file__

prints

/usr/lib/python2.7/os.pyc

on my machine.

To do this before importing a module, you can use imp.find_module():

imp.find_module("os")[1]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
6

sys.modules['path.to.module'].__file__

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> import sys
>>> sys.modules['collections'].__file__
'/usr/lib/python2.7/collections.pyc'
>>>
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • Why use `sys.modules` if you are importing the module into the current namespace anyway? Simply `collections` will do. – Sven Marnach Mar 02 '12 at 14:12
  • @SvenMarnach, you are right, but he has module path, not reference to the module object – warvariuc Mar 02 '12 at 14:15
  • 2
    Well, the OP meanwhile clarified that the module shouldn't be imported at all, so neither `sys.modules['collections'].__file__` nor `collections.__file__` will help. – Sven Marnach Mar 02 '12 at 14:23
  • @Sven: You're correct, I've removed my other comments -- but the OP accepted this answer... – martineau Mar 02 '12 at 14:34
1
path = path.to.module.__file__
janneb
  • 36,249
  • 2
  • 81
  • 97