Importing modules from parent folder

前端 未结 22 2669
梦毁少年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:53

    You could use relative imports (python >= 2.5):

    from ... import nib
    

    (What’s New in Python 2.5) PEP 328: Absolute and Relative Imports

    EDIT: added another dot '.' to go up two packages

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

    Relative imports (as in from .. import mymodule) only work in a package. To import 'mymodule' that is in the parent directory of your current module:

    import os,sys,inspect
    currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    parentdir = os.path.dirname(currentdir)
    sys.path.insert(0,parentdir) 
    
    import mymodule
    

    edit: the __file__ attribute is not always given. Instead of using os.path.abspath(__file__) I now suggested using the inspect module to retrieve the filename (and path) of the current file

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

    Although it is against all rules, I still want to mention this possibility:

    You can first copy the file from the parent directory to the child directory. Next import it and subsequently remove the copied file:

    for example in life.py:

    import os
    import shutil
    
    shutil.copy('../nib.py', '.')
    import nib
    os.remove('nib.py')
    
    # now you can use it just fine:
    nib.foo()
    

    Of course there might arise several problems when nibs tries to import/read other files with relative imports/paths.

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

    I made this library to do this.

    https://github.com/fx-kirin/add_parent_path

    # Just add parent path
    add_parent_path(1)
    
    # Append to syspath and delete when the exist of with statement.
    with add_parent_path(1):
       # Import modules in the parent path
       pass
    
    0 讨论(0)
提交回复
热议问题