سؤال

I have two projects in workspace: PROJECTA and PROJECTB

I added the path of two projects to Environmental Variables with

variable name: PYTHONPATH variable value : C:\path-to-PA\PROJECTA;C:\path-to-PB\PROJECTB;

I have following directory structure for PROJECTA & PROJECTB

PROJECTA
    com
       example
            sample
                projAAA
                   srcfiles
                   testcasefiles


PROJECTB
    com
       example
            sample
                projBBB
                   srcfiles
                   testcasefiles

I am tring to import a file from srcfiles directory from testcasefiles directory in PROJECTB

from com.example.sample.projectBBB.srcfiles import pythonfile.py

Python is throwing an exception:

ImportError: No module named projectBBB.srcfiles

This error won't occur when PROJECTA path is removed from PYTHONPATH in Environmental variables

How to resolve this issue where I can add multiple project paths.

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

المحلول

Well, Python always takes the first occurence of "com" (here in PROJECTA) as the module "com" and doesn't even look for other occurences of "com" if it can't find something inside it. Python doesn't "merge" modules - if you think about it, it makes no sense as the modules can be arbitrarily general and complex.

Solution A (normal)

Include in PYTHONPATH the directory above the projects and address the modules with the prefix, like e.g. this:

from PROJECTA import com as comA
from PROJECTB import com as comB
from comA.example.sample.projectBBB.srcfiles import pythonfile.py

Btw. we are tacitly assuming you have __init__.py files where they should be (i.e. in all directories that should be treated as modules).

Solution B (weird)

Include in PYTHONPATH the directory above the projects as in the previous case, but create a third directory structure like this:

MODULE_MERGE
    com
        example
            sample

Edit the MODULE_MERGE/com/example/sample/__init__.py file to include this:

from comA.example.sample import projAAA
from comB.example.sample import projBBB

And now happily include MODULE_MERGE in your PYTHONPATH

The question is whether it reasonable to do such things. I don't think so. Python projects should be self-contained and usually don't have deeply nested namespaces.

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