Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current import paths in Python?

I get an ImportError exception somewhere in the code, but the same module can be imported safely at startup of the application. I'm curious to see which paths Python looks for modules to import, so that I can trace why this problem occurs. I found this:

print sys.path

Is this the list of ALL paths that system looks when tries to import a module?

like image 938
aligf Avatar asked Apr 22 '11 00:04

aligf


People also ask

What is __ path __ in Python?

If you change __path__ , you can force the interpreter to look in a different directory for modules belonging to that package. This would allow you to, e.g., load different versions of the same module based on runtime conditions.

How does Python find imports?

Step 2: If the module that needs to be imported is not found in the current directory. Then python will search it in the PYTHONPATH which is a list of directory names, with the same syntax as the shell variable PATH. To know the directories in PYTHONPATH we can simply get them by the sys module.


2 Answers

The path locations that python checks by default can be inspected by checking sys.path.

import sys print(sys.path) 
like image 64
Praveen Gollakota Avatar answered Sep 29 '22 08:09

Praveen Gollakota


If you want a bit better formatting:

import sys  from pprint import pprint  pprint(sys.path) 
like image 23
marsh Avatar answered Sep 29 '22 07:09

marsh