0

How can I find the path for a Python module without importing it?

It seems like it should be obvious but I can't find a function to do this. (Yes I double-checked the docs for imp).

Note: I can't import the module. Also this is a python2 specific issue, so I can't use importlib.find_loader.


update per comment: In python3 this can be done with importlib.find_loader which returns an object with a path property, which works for packages and files (unlike imp.find_module).

user3467349
  • 3,043
  • 4
  • 34
  • 61
  • What exactly are you trying to do? – kindall Feb 04 '15 at 02:13
  • I'm trying to find the path of a module without importing it, what exactly merits the downvotes? – user3467349 Feb 04 '15 at 02:15
  • Some background would make your question more understandable. Or if you know how to do it in Python 3, post that code. Why can't you import the module? – paulmelnikow Feb 04 '15 at 03:04
  • @noa I had a stray python3 module loading into python2 on import instead of the one I wanted to load, which was causing syntax errors and I didn't know which path it was on. It's basically not a common use case and I just reverted to shell `find` piped to `grep`, but I thought there should be an accessible function to do this. – user3467349 Feb 04 '15 at 03:14
  • Yeah, it's a good question. I'm not too surprised there isn't a way though. You could always run python3, import it, and print the path. – paulmelnikow Feb 04 '15 at 03:21

1 Answers1

0

Something like this maybe:

import imp
print imp.find_module("mymodule")
kindall
  • 178,883
  • 35
  • 278
  • 309