Get the path on behalf of the module

I am sure there is an easy way to get the module path from modulename, right? That is, I want to extract / path / to / module from path.to.module, preferably in python 2.7.

I do not intend to import the module, and I have modulename as a string.

+4
source share
3 answers

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' >>> 
+6
source

This is pretty easy after importing the module:

 import os print os.__file__ 

prints

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

on my car.

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

 imp.find_module("os")[1] 
+9
source
 path = path.to.module.__file__ 
+1
source

Source: https://habr.com/ru/post/1399398/


All Articles