Reputation:
This is my project structure:
The directory of the Elvvo folder is /home/pi/Desktop/Elvvo
as I am working on a Raspberry Pi.
I have a couple of functions defined in main.py
. I want to call those functions from lights.py
. How do I do this? Thanks in Advance!
Upvotes: 1
Views: 939
Reputation: 6476
You can use the sys.path.insert()
builtin-method to insert the path of main.py to position 1 of the system’s path variable. This ensures that it’s loaded with highest priority and avoids any naming conflicts if present.
Please see how I have solved this below:
My folder structure is as shown below:
import_test
├── functions
│ └── function.py
├── main.py
My main.py
def printFromMainA():
print("FromMainA")
def printFromMainB():
print("FromMainB")
My functions/function.py
import sys
sys.path.insert(1, "Absolute path to import_test/")
from main import *
def printFunction():
print("FromFunction")
printFromMainA()
printFromMainB()
printFunction()
And then finally when I run from import_test
folder
python functions/function.py
I get the following output:
FromFunctionA
FromMainA
FromMainB
You can also use the sys.path.append()
method which appends the path of the main.py to the system’s path variable. This will add the current path to the last position of the system’s paths list.
In this case all you need to do to the function.py is:
import sys
sys.path.append("Absolute path to import_test/")
from main import *
def printFunction():
print("FromFunction")
printFromMainA()
printFromMainB()
printFunction()
This should also give you the desired output.
Upvotes: 1