如何在Python中为项目中的所有脚本执行目录引用

如何在Python中为项目中的所有脚本执行目录引用,python,python-3.x,subdirectory,referrals,Python,Python 3.x,Subdirectory,Referrals,我现在在做Python已经有一段时间了,但这是我第一次在一个项目中使用相互引用的不同脚本来准备它。文件的结构如下(简化): 因为script2和script3都在Script1中使用函数,所以我现在在script2和script3中都做类似的事情: main_dir = os.path.dirname(os.path.realpath(__file__)) modules_dir = os.path.realpath(os.path.join(main_dir, '..', '..')) sys

我现在在做Python已经有一段时间了,但这是我第一次在一个项目中使用相互引用的不同脚本来准备它。文件的结构如下(简化):

因为script2和script3都在Script1中使用函数,所以我现在在script2和script3中都做类似的事情:

main_dir = os.path.dirname(os.path.realpath(__file__))
modules_dir = os.path.realpath(os.path.join(main_dir, '..', '..'))
sys.path.insert(0, modules_dir)

from folder1.folder1a.script1 import function1

问题是:这样我就需要把这些代码放在每个脚本中,这不是很方便。我有一个设置脚本,所以也许我可以把参考代码放在那里。我只是不知道如何以一种最整洁、最有效的方式来做。有人能帮我吗?

这应该会有帮助:谢谢你,这真的很有帮助!这应该有帮助:谢谢你,这真的很有帮助!
main_dir = os.path.dirname(os.path.realpath(__file__))
modules_dir = os.path.realpath(os.path.join(main_dir, '..', '..'))
sys.path.insert(0, modules_dir)

from folder1.folder1a.script1 import function1