How to get current import paths in Python?
The path locations that python checks by default can be inspected by checking sys.path
.
import sysprint(sys.path)
If you want a bit better formatting:
import sysfrom pprint import pprintpprint(sys.path)
The other answers are almost correct
Python 3:
import sysimport_paths = sys.path
In Python 2.7:
import sysimport osimport copyimport_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.