2
`-- MyDir
|-- FolderA
|   |-- __init__.py
|   |-- ScriptA.py
`-- FolderB
    |-- __init__.py
    |-- ScriptB.py

The above is an example of my current structure. In both FolderA and FolderB, there are .from FolderX import * in __init__.py, X is A or B.

I want to run ScriptB.py which imports FolderA first: from FolderA import *. However, executing python ScriptB.py under FolderB reports ModuleNotFoundError: No module named 'FolderA';

My current workaround to get this work is typing export PYTHONPATH=/path/to/MyDir:$PYTHONPATH every time I start the conda environment. I would like to ask for the reason behind this and how could one avoid doing this way.

EDIT: it seems that I should have used Folder and Script to keep simplicity.

Francis
  • 6,416
  • 5
  • 24
  • 32

3 Answers3

2

If PackageA and PacakgeB at the same directory level you can just add __init__.py in that directory too:

App
----__init__.py
----PackageA
---- ...
--------__init__.py
----PackageB
---- ...
--------__init__.py

Otherwise, if those packages are independently developed that you can install them as global packages.

CristiFati
  • 38,250
  • 9
  • 50
  • 87
ybl
  • 1,510
  • 10
  • 16
  • I don't know if I understand it correctly, but simply adding `__init__.py` under MyDir doesn't work. – Francis Jan 22 '19 at 01:16
0

I can see a few ways to tackle this. First, I would consider the possibility of making them a single package. But that can be quickly discarded if they clearly are not.

If they truly are separate packages, you still have options. If one is ready to be released, you can surely install it to your Python environment via pip install using a setup.py script and all things associated with it. See Python packaging tutorial for more info.

Finally, and most likely you are still planning on modifying the contents. In that case pip has a very handy ability to install a package as a symbolic link. This way the package is read from the directory that you develop on. It is done by executing pip install -e . from the directory where setup.py exists. You can have a common setup script for "both" packages, using e.g. setuptools.find_packages. Or you can modify the folder structure slightly to have a different setup for each package. Now they are importable as normal Python packages.

Felix
  • 2,548
  • 19
  • 48
0

Use conda develop

https://conda.io/docs/commands/build/conda-develop.html

This allows you to add a directory to a conda.pth file in site-packages of the environment of your choosing, which will be added to your pythonpath automatically.

conda develop ~/path/to/work_in_progress/code/ -n environment_name
emmet02
  • 932
  • 5
  • 8