4

I'm trying to import a package from a different project, but it's not recognising the project that I'm trying to import from. I've looked at various answers to this question (including python: import another project module named same with a local module).

My project structure looks like this:

Project1
 - __init__.py
 - foo_directory
  - foo.py
  - __init__.py


Project2
 - __init__.py
 -bar_directory
  - bar.py
  - __init__.py

In bar.py I'm trying to do:

import sys
sys.path.append('path/to/Project2')

from Project1.foo_directory import foo.py

I can't work out why it's not recognising Project1 when I try to do an import?

Community
  • 1
  • 1
ChrisG29
  • 1,321
  • 3
  • 22
  • 41
  • maybe this helps: http://stackoverflow.com/a/30625670/4954037 – hiro protagonist May 19 '17 at 13:11
  • Possible duplicate of [Importing Python modules from different working directory](http://stackoverflow.com/questions/1046628/importing-python-modules-from-different-working-directory) – Mike - SMT May 19 '17 at 13:12

3 Answers3

4

You should create two packages, Project1 and Project2 (note the setup.py)

Project1
 - setup.py
 - Project1
  - __init__.py
  - foo_directory
   - foo.py
   - __init__.py

and

Project2
 - setup.py
 - Project2
  - __init__.py
  - bar_directory
   - bar.py
   - __init__.py

then install them

pip install -e Project1/
pip install -e Project2/

And then you can simply do

from Project1.foo_directory import foo

The obvious advantage: Package2 depends on Package1 but doesn't need to know where it was installed. Managing all the import paths is done by pip and the environment you're in (hopefully a virtualenv).

Nils Werner
  • 31,964
  • 7
  • 67
  • 91
  • if i don't put Project2 inside Project 1, i get `.. should either be a path to a local project or a VCS url beginning with svn+, git+, hg+, or bzr+` , local package must be inside the parent package to install? – TomSawyer Apr 15 '19 at 03:00
  • @TomSawyer please open a new question – Nils Werner Apr 15 '19 at 05:11
1

Based on the advice Maresh gave me, I did the following (I'm using Windows, which is why I couldn't follow his answer exactly):

In PyCharm: File > Settings > Project: Project1 > Project Structure. - Add Content Root (add the location for Project2). - Apply and OK

Then in bar.py I was able to import files from Project2

ChrisG29
  • 1,321
  • 3
  • 22
  • 41
0

2 Solutions:

1- Use the PYTHONPATH environoment variable. See this answer for more details

$ export PYTHONPATH=$(PYTHONPATH):/path/to/project1 

2 - Create a setup.py for your projects so you can install them, thus import them>

https://docs.python.org/3/distutils/setupscript.html

Note: Messing with the sys.path from within app is not a recommanded solution as it is not really robust not crossplatform.

Community
  • 1
  • 1
Maresh
  • 4,486
  • 21
  • 29