Importing modules from a neighbouring folder in Python

前端 未结 3 1259
眼角桃花
眼角桃花 2020-12-16 17:06

I have put the question in the figure below:

EDIT The question put next to the figure is:

How do I make script_A1 import a function

相关标签:
3条回答
  • 2020-12-16 17:20

    You can use a trick of adding the top folder to path:

    import sys
    sys.path.append('..')
    import folderB.something
    

    You can also use imp.load_source if you prefer.

    0 讨论(0)
  • 2020-12-16 17:24

    I think I solved the issue.

    In the following way, you can append the parent directory to the PATH. Put this at the top of script_A1:

    import sys
    import os
    myDir = os.path.dirname(os.path.abspath(__file__))
    parentDir = os.path.split(myDir)[0]
    if(sys.path.__contains__(parentDir)):
        print('parent already in path')
        pass
    else:
        print('parent directory added')
        sys.path.append(parentDir)
    
    # Now comes the rest of your script
    

    You can verify that the parent directory myProject is indeed added to the PATH by printing out:

        print(sys.path)
    

    Since the parent directory myProject is now part of the PATH, you can import scripts/modules/whatever from any of its subdirectories. This is how you import script_B2 from folder_B:

    import folder_B.script_B2 as script_B2
    

    After closing your application, you can verify if your Python environment is restored to its initial state. just print the PATH again and check if the directory you had appended is gone.

    0 讨论(0)
  • 2020-12-16 17:26

    Put this at the top of script_A1;

    from folderB.script_B2 import YourClass as your_class

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