简体   繁体   English

从常见目录导入Python

[英]Python Imports from common directories

We have multiple projects using common python code. 我们有多个使用通用python代码的项目。

File Structure:

Parent_folder
--Project_folder
  --Project_A
    --(source code)
  --Project_B
    --(source code)
--Common_folder
  --Common_library_A
    --__init__.py
    --(source code)
  --Common_library_B
    --__init__.py
    --(source code)

For Project_A to import Common_library_A I can use: 为了使Project_A导入Common_library_A,我可以使用:

 path = os.path.join(dirname(abspath(__file__)),"\\..\\..\\Common_folder\\")
 sys.path.append(path)
 import common_library_A

or I can look for 'parent_folder' on the current working directory, and use that as a base path to add common_folder to, which I then add to the sys path. 或者我可以在当前工作目录中查找“ parent_folder”,并将其用作添加common_folder的基本路径,然后将其添加到sys路径。

We can't use a fixed path, as different branches will need to use the version of the code in their branch. 我们不能使用固定路径,因为不同的分支将需要在其分支中使用代码的版本。

Is there a 'cleaner' way of doing this? 有没有一种“清洁”的方式来做到这一点?

I think it is ok. 我认为还可以。 If you encounter problems you can change it. 如果遇到问题,可以更改它。

Usually the common_folder is called site-packages. 通常,common_folder称为站点包。 common_library_A and common_library_B would be installed separately into the site-packages folder. common_library_A和common_library_B将分别安装到site-packages文件夹中。

But if you work in a version-control-system and everything in Parent_folder should be of the same version, then site-packages is no solution. 但是,如果您在版本控制系统中工作,并且Parent_folder中的所有版本都应为同一版本,那么解决方案不是站点包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM