问题描述:

My file directory tree looks like this:

my_repo

├── experiments

│ ├── foo.py

│ └── __init__.py

└── tests

├── baz.py

└── __init__.py

Inside baz.py, I try

from experiments.foo import FooExperiment

but I get

*** ImportError: No module named experiments.foo

When I open python from the terminal (Mac OSX 10.9) and run

from experiments.foo import FooExperiment

the class is imported properly. What is going on? Please help.

In both situations the sys.path is exactly the same, except when I'm in baz.py the current path (to baz.py) is included. And yes /path/to/my_repo is in my sys.path as well.

EDIT: my issue was with conflicting egg files, so reinstalling did the trick (below). Accepting @Austin Marshall's answer though because it's a viable solution to the general case of this problem.

pip uninstall my_repo

python setup.py develop --user

网友答案:

experiments is not in PYTHONPATH, nor is it installed using the standard setuptools technique. I'm able to replicate your problem, which is resolved by putting my_repo in PYTHONPATH:

Austins-MacBook-Pro-2:my_repo amarshall$ tree .
.
├── experiments
│   ├── __init__.py
│   └── foo.py
└── tests
    ├── __init__.py
    └── baz.py

2 directories, 4 files
Austins-MacBook-Pro-2:my_repo amarshall$ PATH=$PATH:`pwd`/experiments python tests/baz.py 
Traceback (most recent call last):
  File "tests/baz.py", line 1, in <module>
    from experiments.foo import FooExperiment
ImportError: No module named experiments.foo
Austins-MacBook-Pro-2:my_repo amarshall$ PYTHONPATH=$PYTHONPATH:`pwd` python tests/baz.py 

Where there's no output, or error in the last line when PYTHONPATH is specified, rather than PATH

网友答案:

I usually use the following to append path to sys.path:

sys.path.append(os.path.join(os.path.dirname(__file__), "../myfolder"))

With

Import sys, os
相关阅读:
Top