How to get current import paths in Python?

后端 未结 4 568
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:22

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

    0 讨论(0)
  • 2020-12-08 04:27

    If you want a bit better formatting:

    import sys
    
    from pprint import pprint
    
    pprint(sys.path)
    
    0 讨论(0)
  • 2020-12-08 04:34

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

    import sys
    print(sys.path)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题