简体   繁体   中英

Python import from beyond top-level package

I am developing a Django project for which I wrote some non-web related libraries.

My directory structure looks something like this:

Main folder

  • Theorem prover
    • here are the things I want to import
  • web
    • app
      • here's where I want to import things from

The place where I'm running the app is the web/ folder. What would be the proper way of doing this?

You can add Theorem prover folder to your PYTHONPATH . Either setting the environment variable prior to app launch, or by

import sys
sys.path.insert(0, '/path/to/theorem')

Before importing the theorem related modules.

  • Make sure, that your settings.py which located at the project root directory, has sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  • from web -> app -> here's where I want to import things from:
    import Theorem_prover.here_are_the_things_I_want_to_import

Use importlib .

importlib.import_module(name, package=None)

Import a module. The name argument specifies what module to import in absolute or relative terms (eg either pkg.mod or ..mod ). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (eg import_module('..mod', 'pkg.subpkg') will import pkg.mod).

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