How to get current import paths in Python?

自闭症网瘾萝莉.ら 提交于 2019-11-28 06:11:42
Praveen Gollakota

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

import sys
print(sys.path)
marsh

If you want a bit better formatting:

import sys

from pprint import pprint

pprint(sys.path)

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').

Christopher Pratt

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!