Sebastian
Sebastian

Reputation: 1111

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!

Upvotes: 0

Views: 31

Answers (2)

Sebastian
Sebastian

Reputation: 1111

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

Upvotes: 0

Regetix
Regetix

Reputation: 39

You may write your code like this:

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

You can also check your current directory while using pipenv run by adding the following lines code to your current code:

import os
######Your code here######
os.system('pwd')

This will print current directory where it has executed from. (using os.curdir won't help cause it will show a single dot)

Upvotes: -1

Related Questions