How to get current import paths in Python?

Python Programming

Question or problem about Python programming:

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?

How to solve the problem:

Solution 1:

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

import sys
print(sys.path)

Solution 2:

If you want a bit better formatting:

import sys

from pprint import pprint

pprint(sys.path)

Solution 3:

The other answers are almost correct

Python 3:

import sys
import_paths = sys.path

In Python 2.7:

import sys
import os
import copy
import_paths = copy.copy(sys.path)
if '__file__' in vars(): import_paths.append(os.path.abspath(os.path.join(__file__,'..')))

In both versions the main file (i.e. __name__ == '__main' is True) automatically adds its own directory to sys.path. However Python 3 only imports modules from sys.path. Python 2.7 imports modules from both sys.path AND from the directory of the current file. This is relevant when you have a file structure like:

|-- start.py
|-- first_import
|   |-- __init__.py
|   |-- second_import.py

with contents
start.py:
import first_import
__init__.py:
import second_import.py

In Python 3 directly running __init__.py will work, but when you run start.py, __init__.py wont be able to import second_import.py because it wont be in sys.path.

In Python 2.7 when you run start.py, __init__.py will be able to import second_import.py even though its not in sys.path since it is in the same folder as it.

I cant think of a way to perfectly duplicate Python 2.7’s behavior in Python 3 unfortunately.

Solution 4:

Sys.path is a list of all the paths Python looks through when finding imports. If you want to add another path to a directory containing one or more python files, you can use: sys.path.append('path/to/directory').

Hope this helps!