pythonpython-3.xpipenv

Run Python script from shell script, with Virtualenv, and as module with -m


How can I run a Python script from a shell script, with the conditions:

  1. it uses a helper script from a parallel folder
  2. it uses the virtual environment for its subfolder

My file/folder structure looks like this:

project_folder
  -subfolder_prog_1
    -prog1.py
  -subfolder_prog_2
    -prog2.py
  -helpers
    -helper.py

Each of the subfolder_prog_x uses their own virtual environment (pipenv).

prog1.py and prog2.py use helper.py like this:

from helpers.helper import helpful_function

Now - I know I can activate the environment from the shell like this:

cd ~/git/project_folder/subfolder_prog_1
pipenv run python prog1.py

I also know that if I want to use an import from a parallel folder I have to run the script as a module, from the parent folder like this:

cd ~/git/project_folder/
python -m subfolder_prog_1.prog1

But how can I combine the two?

I tried

cd ~/git/project_folder/
pipenv run python -m subfolder_prog_1.prog1

but that gets me a ModuleNotFoundError: No module named 'subfolder_prog_1'.

All hints are appreciated!


Solution

  • Found the answer, inspired by this question: It works if you use the PIPFILE setting to set the path to your Pipfile:

    cd ~/git/project_folder
    PIPENV_PIPFILE=subfolder_prog_1/Pipfile pipenv run python -m subfolder_prog_1.prog1