0

I'm having some issues importing modules.

The project structure is something like:

xpr01
---- xpr02
     ---- __init__.py
     ---- folder01
          ---- app_helpers.py
          ---- data_manipulation.py

     ---- folder02
          ---- main.py

In order to run main.py (which is in folder02), I need some functions defined in the modules contained in folder01.

So, when using PyCharm I set xpr01 as working directory, and in main.py I'm using:

from xpr02.folder01.data_manipulation import get_policies, get_categories, get_country_data
from xpr02.folder01.data_manipulation import get_plan_df, get_all_plans_df

And everything works just fine. However, when I try running it from terminal (Ubuntu 18.04), I get the error:

ModuleNotFoundError: No module named 'xpr02'

I assume the issue is that I should do...something which has the same effect as specifying the working directory in PyCharm. I was assuming having the init.py under xpr02 would do it, but apparently I'm wrong.


EDIT

PyCharm is executing the command:

/home/my_home_folder/anaconda3/envs/myenv/bin/python /home/my_home_folder/projects/xpr01/xpr02/folder02/main.py

While I was simply running:

python main.py

from within folder02. I tried running the same command as in PyCharm (with all the absolute paths), but I'm still getting the same error.

Carlo
  • 1,008
  • 9
  • 20
  • Could you send the command PyCharm executes on the terminal to run and the command you write in the terminal? – electromeow Apr 16 '21 at 11:19
  • Looks like a [path](https://www.devdungeon.com/content/python-import-syspath-and-pythonpath-tutorial#:~:text=When%20you%20call%20import%20in,modify%20the%20PYTHONPATH%20environment%20variable.) issue – Ceres Apr 16 '21 at 11:21
  • I updated the question to reply to electromeow. Ceres, I imagined it was the case, but as I wrote I was expecting that having the __init__.py in folder02 would fix it – Carlo Apr 16 '21 at 11:33
  • 2
    Does this answer your question? [How to import other Python files?](https://stackoverflow.com/questions/2349991/how-to-import-other-python-files) – bad_coder Apr 17 '21 at 14:18
  • @Carlo see [The Module Search Path](https://docs.python.org/3/tutorial/modules.html#the-module-search-path) whatever directory you are executing from gets automatically put on `sys.path`. That's why executing on the path just underneath the package allows to import it. To make the package available install it to the venv and then you can execute from anywhere if you have the venv activate. – bad_coder Apr 17 '21 at 14:21

2 Answers2

1

try using

sys.path.append(path_to_folder_containing_python_code)

0

If when you created the folder you created xpr02 as a python module or package pycharm sets PYTHONPATH.

Writing this way too early in the morning, so exaxct path might be wrong, but try setting PYTHONPATH to /home/my_home_folder/projects.

mpechner
  • 119
  • 7