4

I need to know where a code object comes from ; its module. So I (naively) tried :

os.path.abspath(code.co_filename)  

But that may or may not work, (I think it's because abspath depends on cwd)

Any way to get the full path of a code object's module ?

EDIT :
The functions from the inspect module : getfile, getsourcefile, getmodule, get only the file name, not its path (same thing as co_filename). Maybe they use abspath.

dugres
  • 12,613
  • 8
  • 46
  • 51

3 Answers3

3
import inspect
print inspect.getfile(inspect)
Mariy
  • 5,746
  • 4
  • 40
  • 57
1

The inspect.getsourcefile() function is what you need, it returns the relative path to the file where the object's source can be found.

mdeous
  • 17,513
  • 7
  • 56
  • 60
  • inspect.getsourcefile(os.path) returned me '/usr/lib/python2.7/posixpath.py' (it seems the returned path is either relative or absolute depending on the context). – mdeous Aug 19 '11 at 15:21
  • yes, it depends on the context (like abspath), and that's the problem, I couln't rely on it. – dugres Aug 19 '11 at 15:24
  • `os.path.realpath(inspect.getsourcefile(obj))` seems to do what you want – mdeous Aug 19 '11 at 15:27
  • realpath seems to depend also on the context – dugres Aug 19 '11 at 15:33
0

If you have access to the module, try module.__file__.

>>> import xml
>>> xml.__file__
'/usr/local/lib/python2.6/dist-packages/PyXML-0.8.4-py2.6-linux-i686.egg/_xmlplus/__init__.pyc'

If you don't, something like this should work:

>>> import xml.etree.ElementTree as ET
>>> thing = ET.Element('test')
>>> __import__(thing.__module__).__file__
'/usr/local/lib/python2.6/dist-packages/PyXML-0.8.4-py2.6-linux-i686.egg/_xmlplus/__init__.pyc'

In this case, we are using the fact that import can be called on the string version of the module, which returns the actual module object, and then calling __file__ on that.

Brent Newey
  • 4,479
  • 3
  • 29
  • 33