How to get current import paths in Python?

后端 未结 4 569
Happy的楠姐
Happy的楠姐 2020-12-08 03:50

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

4条回答
  •  爱一瞬间的悲伤
    2020-12-08 04:47

    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.

提交回复
热议问题