سؤال

I am structuring my Python application with the following folder architecture (roughly following the outline here):

myapp:
    myapp_service1:
        myapp_service1_start.py
        ...
    myapp_service2:
        myapp_service2_start.py
        ...
    myapp_service3:
        myapp_service3_start.py
        ...
    common:
        myapp_common1.py
        myapp_common2.py
        myapp_common3.py
        ...
scripts:
    script1.py
    script2.py
    script3.py
    ...
tests:
    ...
docs:
    ...
LICENSE.txt
MANIFEST.in
README

This is ideal file/folder hierarchy for me, however, I am confused on how to reference modules from outside folders. For instance, myapp_service1_start.py needs to reference function in myapp_common1.py and myapp_common2.py.

I know I need to somehow add reference to the system path or pythonpath, but I'm not sure the best way to do this in code. Or rather where I would even do this in code.

How can I do this?

I've seen a lot of posts about creating a full Python package to be installed via pip, but this seems like overkill to me.

هل كانت مفيدة؟

المحلول

One way is to make each of your myapp_service*_start.py files add myapp/ directory to sys.path.

For example, drop a file called import_me.py into myapp_service1/ with code that appends the "one up" directory (relative to importing file) to sys.path:

import os
import sys
import inspect
this_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
src_dir = os.path.join(this_dir, '..')
sys.path.insert(0, src_dir)

Then, in your myapp_service1_start.py you can do something like:

import import_me
from common import myapp_common1
from common import myapp_common2

Of course, be sure to make common directory a Python package by dropping a (possibly empty) __init__.py file into it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top