14
votes

I have put the question in the figure below:

enter image description here

EDIT The question put next to the figure is:

How do I make script_A1 import a function from script_B2?

Similar questions have been asked before. But most answers suggest to add the module/script/package(whatever) to the PATH variable. For example:

sys.path.append('...')

But adding the module to the PATH variable just feels so wrong. I do not want to alter my system in any way. When my application closes, I want my Python environment to be clean and 'untouched'. I'm afraid that adding uncontrolled modules to the PATH variables on my system will cause headaches later on.

Thank you for helping me out :-)

3
Appending to sys.path isn't a persistent change; it won't do anything to PATH or PYTHONPATH. It's probably not the best way to go about this, but it's not going to have the problems you're worried about. - user2357112 supports Monica
I don't know why someone downvoted my question. Please, leave a comment before making the downvote, to explain what I can do better. I'm a reasonable person. I'm willing to listen. - K.Mulier
Your answer should be in text form, not uploaded as an image: meta.stackoverflow.com/questions/318618/… - Darrick Herwehe
Yeah, I've put a lot of text next to the figure.. - K.Mulier
@K.Mulier that text is not searchable by google and other site crawlers. Your question should be in actual text. You have put your text in an image, which helps no one. - Darrick Herwehe

3 Answers

6
votes

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
votes

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.

-1
votes

Put this at the top of script_A1;

from folderB.script_B2 import YourClass as your_class