Importing modules from parent folder

前端 未结 22 2670
梦毁少年i
梦毁少年i 2020-11-21 23:19

I am running Python 2.5.

This is my folder tree:

ptdraft/
  nib.py
  simulations/
    life/
      life.py

(I also have __init

相关标签:
22条回答
  • 2020-11-21 23:44

    Work with libraries. Make a library called nib, install it using setup.py, let it reside in site-packages and your problems are solved. You don't have to stuff everything you make in a single package. Break it up to pieces.

    0 讨论(0)
  • In a Linux system, you can create a soft link from the "life" folder to the nib.py file. Then, you can simply import it like:

    import nib
    
    0 讨论(0)
  • 2020-11-21 23:46

    import sys sys.path.append('../')

    0 讨论(0)
  • 2020-11-21 23:47

    If adding your module folder to the PYTHONPATH didn't work, You can modify the sys.path list in your program where the Python interpreter searches for the modules to import, the python documentation says:

    When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

    • the directory containing the input script (or the current directory).
    • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
    • the installation-dependent default.

    After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.

    Knowing this, you can do the following in your program:

    import sys
    # Add the ptdraft folder path to the sys.path list
    sys.path.append('/path/to/ptdraft/')
    
    # Now you can import your module
    from ptdraft import nib
    # Or just
    import ptdraft
    
    0 讨论(0)
  • 2020-11-21 23:47

    same sort of style as the past answer - but in fewer lines :P

    import os,sys
    parentdir = os.path.dirname(__file__)
    sys.path.insert(0,parentdir)
    

    file returns the location you are working in

    0 讨论(0)
  • 2020-11-21 23:48

    The pathlib library (included with >= Python 3.4) makes it very concise and intuitive to append the path of the parent directory to the PYTHONPATH:

    import sys
    from pathlib import Path
    sys.path.append(str(Path('.').absolute().parent))
    
    0 讨论(0)
提交回复
热议问题