My project space is something like this:
Project
Functions_Folder/
__init__.py
Folder1/
__init__.py
Function1.py
Function2.py
Function3.py
Folder2/
__init__.py
Function4.py
Function5.py
Function6.py
Codes_Folder/
script1.py
script2.py
I need to import in script1.py
some functions of the Folder1
and Folder2
but that functions also have to import functions on the same directory, i mean, for example Function4.py
has to import Function6.py
and Function3.py
Please help.
You can use relative import
├── test
│ ├── __init__.py
│ ├── a
│ │ ├── one.py
│ │ └── two.py
│ └── b
│ ├── __init__.py
│ └── one.py
└── test.py
in which the one.py
file in module a
is simply
from .two import a_two
def a_one(i):
return 10*a_two(i)
the two.py
file in module a
is
def a_two(i):
return 5*i
the one.py
file in module b
is
from ..a.one import a_one
def b_one(i):
return a_one(i)
The lines from ..a.one import a_one
and from .two import a_two
use relative import.
The whole module can be tested by running the test.py
file, which is
from test.b.one import b_one
print(b_one(1))
As for the problem of importing the module test
in a script, in macOS and linux, you need to set PYTHONPATH
in .bashrc
for the module test
with
export PYTHONPATH=the_path_to_module_test:$PYTHONPATH
So you want to import some functions from Folder1
and Folder2
in script1.py
.
First create __init__.py
for the Project
folder
script1.py
import sys
sys.path.append("..")
from Functions_folder.Folder1 import Function1, Function2
from Functions_folder.Folder2 import Function4, Function5
Function4.py
import sys
sys.path.append("..")
from Folder2 import Function5, Function6
from Folder1 import Function3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.