一、结构设计
设计 了一个足够复杂的文件情况(如上和如下),其中,a.py和aa.py之类函数模块,test_a.py和test_aa.py分别为引用的模块。这样看看,他们之间是如何引用的,有什么规律。
D:\POC_A
│ a.py
│ test_a.py
│
├─poc_aa
│ │ aa.py
│ │ test_aa.py
│ │
│ └─poc_aaa
│ aaa.py
│ test_aaa.py
│
├─poc_bb
│ │ bb.py
│ │ test_bb.py
│ │
│ └─poc_bbb
│ bbb.py
│ test_bbb.py
│
└─poc_cc
cc.py
二、代码
其中,aa.py,aaa.py的代码为类似格式代码,其它也类似,具体如下:
aa.py
## aa.py
import os
def print_aa():
print(f"i am poc_aa, my path : {os.getcwd()}!")
aaa.py
import os
# aaa.py
def print_aaa():
print(f"i am poc_aaa, my path : {os.getcwd()}!")
bb.py
import os
# bb.py
def print_bb():
print(f"i am poc_bb, my path : {os.getcwd()}!")
三、一种方案
我们在同级的test_a.py、test_aa.py,test_aaa.py等中,调用不用的a.py,aa.py,aaa.py,bb.py,bbb.py。。。。看看需要如何安排?
import os
import sys
def get_all_dirs(direction):
dir_list=[]
if os.path.isdir(direction):
dir_list.append(direction)
else:
return dir_list
paths = [os.path.join(direction,file) for file in os.listdir(direction)]
print(f"path : {paths}")
for path in paths:
if os.path.isdir(path):
dir_list.append(path)
_paths = get_all_dirs(path)
for _path in _paths:
dir_list.append(_path)
return dir_list
def sys_append_path(direction):
paths = get_all_dirs(direction)
for path in paths:
sys.path.append(path)
sys_append_path("D:\poc_a")
from aaa import print_aaa #![平级]同级调用,aaa不是文件夹,不能用 "."
from aa import print_aa
from a import print_a
from bb import print_bb
from cc import print_cc
#! test_aaa.py -> d:\poc_a\poc_aa\poc_aaa\test_aaa.py
print(f"--------------start-----------------\n")
print(f"current run py file : {os.path.abspath(__file__)}")
print_a()
print_bb()
print_aa()
print_aaa()
print_cc()
output:
current run py file : D:\poc_a\poc_aa\poc_aaa\test_aaa.py
i am poc_bbb, i am called by others! my path : D:\poc_a\a.py !
i am poc_bb, i am called by others! my path : D:\poc_a\poc_bb\bb.py!
i am poc_aa, i am called by others ! my path : D:\poc_a\poc_aa\aa.py!
i am poc_aaa, i am called by others! my path : D:\poc_a\poc_aa\poc_aaa\aaa.py!
i am poc_cc, i am called by others! my path : D:\poc_a\poc_cc\cc.py !