简体   繁体   中英

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.

If I just copy the file into the pyhton working directory it works fine with:

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

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 .

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. 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.

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

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.

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