简体   繁体   English

python:将其他目录中的文件包含到项目中

[英]python: include files from other directories into a project

I have multiple python projects which should use a number of shared files but I can not figure out how to do this in python. 我有多个应该使用多个共享文件的python项目,但我不知道如何在python中执行此操作。

If I just copy the file into the pyhton working directory it works fine with: 如果我只是将文件复制到pyhton工作目录中,则可以正常使用:

from HBonds import calculateHBondsForSeveralReplicas, compareSameShapeHBMatrices, calculateHBonds

But I do not want to copy it. 但我不想复制它。 I want to include it from: /home/b/data/pythonWorkspace/util/HBonds 我想从以下位置包括它:/ home / b / data / pythonWorkspace / util / HBonds

For me it would make sense to do it like this (but it does not work): 对我来说,这样做是有意义的(但它不起作用):

from /home/b/data/pythonWorkspace/util/HBonds/HBonds.py import calculateHBondsForSeveralReplicas, compareSameShapeHBMatrices, calculateHBonds

How can I do this? 我怎样才能做到这一点?

For 3rd-party libraries, it's best to install them the stock way - either to the system's site-packages or into a virtualenv . 对于第三方库,最好以库存方式安装它们-既可以安装到系统的site-packages ,也可以安装到virtualenv

For project(s) you're actively developing at the machine where it's running, a maintainable solution is to add their root directory(ies) to PYTHONPATH so that you can import <top_level_module>.<submodule>.<etc> from anywhere. 对于正在运行机器的项目,一个可维护的解决方案是将其根目录添加到PYTHONPATH以便您可以从任何位置import <top_level_module>.<submodule>.<etc> That's what we did at my previous occupation. 那就是我们在上一份工作中所做的。 The main plus here is trivial code base update and switch. 这里的主要优点是琐碎的代码库更新和切换。

Another way is to use relative imports , but it's intended for intra-package references, so that you don't have to reiterate the package's name everywhere. 另一种方法是使用相对导入 ,但它是用于包内引用的,因此您不必在任何地方重复包的名称。 If many otherwise unrelated parts of the code use the same module(s), it's probably more convenient to make the shared part a separate package which would be a dependency for all of them. 如果代码中许多其他不相关的部分使用相同的模块,则将共享的部分制作为单独的程序包可能会更方便,这对于所有程序包都是依赖的。

You have to make sure the PYTHONPATH includes the path to that directory as it was pointed out in previous answer. 您必须确保PYTHONPATH包含该目录的路径,如先前答案中所指出的那样。

Or you can use a nastier way: make it available at runtime with piece of code like this. 或者,您可以使用更简单的方法:使用类似这样的代码使其在运行时可用。

import os
import sys

folder = os.path.dirname('/home/b/data/pythonWorkspace/util/')

if dossier not in sys.path:
    sys.path.append(folder)

from HBonds import HBonds

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

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