1

I have a file called setup.sh which basically has this

python3 -m venv env
source ./env/bin/activate

# other setup stuff

When I run sh setup.sh, the environment folder env is created, and it will run my #other setup stuff, but it will skip over source ./env/bin/activate, which puts me in my environment.

The command runs just fine if I do so in the terminal(I have a macbook), but not in my bash file.

Three ideas I've tried:

  1. ensuring execute priviges: chmod +x setup.sh
  2. change the line source ./env/bin/activate to . ./env/bin/activate
  3. run the file using bash setup.sh instead of sh setup.sh

Is there a smarter way to go about being put in my environment, or some way I can get the source to run?

granduser
  • 67
  • 7
  • 1
    You have multiple solutions explained here [how-to-source-virtualenv-activate-in-a-bash-script](https://stackoverflow.com/questions/13122137/how-to-source-virtualenv-activate-in-a-bash-script) – Paul Feb 08 '21 at 21:09
  • https://stackoverflow.com/search?q=%5Bvirtualenv%5D+activate+from+script – phd Feb 08 '21 at 21:16

2 Answers2

0

Unfortunately, you can't really do this with a bash script. When you execute a bash script, it runs inside it's own shell, and when it exits it drops that shell and returns you to the shell you started from.

Thus, if you were to do something inside your script such as set an environment variable, you would see that it was not set once you left the script. Note that this is different than if you source a file, which is effectively what you see with your bashrc/profile files when a shell is started for you.

In your given script, the python environment will be activated for the lifetime of the script, and no longer. You probably should look at programs like pyenv that can look at directory files and seamlessly join you to the correct python environment.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
0

You need a shebang(#!) at the top of your sh file, like so:

#!/bin/sh
source ABSOLUTE_PATH/env/bin/activate
# virtualenv is now active.
#
python3 ABSOLUTE_PATH/script.py
#
# other setup stuff

Insert the paths to the files from the root. Then, make the file executable with chmod 755. Then it can be run by double clicking the file.

If you're just looking to debug code, consider downloading an IDE (i.e. PyCharm CE) that will activate the virtual environment upon opening each project.

jWhiteside
  • 127
  • 5