0

I am trying to write a bash script which runs a couple of python management commands overnight.

I read from other posts that you need to source the virtualenv to be able to import the environment variables, however even after having added the command it still does not work:

#!/bin/bash
source /home/DDiran/.virtualenvs/envname/bin/activate && cd 
/home/DDiran/projectdir/ && python manage.py randomize_product_order && 
python manage.py update_product_prices

The var in question is $PRODUCTION_ENV and it results empty (raising a python KeyError: None)

What am I doing wrong, and why?

EDIT

As requested by @Romeo Ninov, contents of bin/activate: https://pastebin.com/7yAbZxrX

The environment variables are set in bin/postactivate which is set to run immediately after bin/activate I think? That's how it usually works when activating the virtualenv.

6
  • What is the content of /home/DDiran/.virtualenvs/envname/bin/activate? Feb 16, 2018 at 10:28
  • @RomeoNinov edited post with source code of activate
    – DDiran
    Feb 16, 2018 at 11:07
  • So when you run source /home/DDiran/.virtualenvs/envname/bin/activate on it's own, can you echo $PRODUCTION_ENV and get the required output? Feb 16, 2018 at 11:12
  • @RamanSailopal Nope it doesn't work...
    – DDiran
    Feb 16, 2018 at 11:14
  • There is no $PRODUCTION_ENV variables referenced in bin/activate? Feb 16, 2018 at 11:19

1 Answer 1

0

After conducting further research I found two different solutions. I'll post it here for anyone who has a similar issue in future:

Solution #1

As per this post on AskUbuntu, the actual script itself needs to be sourced, so instead of:

bash myscript.sh

It needs to be:

source myscript.sh

Full explanation of why this needs to happen is in the link above.

Solution #2

Is a lot easier. Instead of activating the virtual environment and running:

python manage.py my_command

You simply run:

/path/to/virtual/env/bin/python manage.py my_command

This way you don't have to worry about activating the virtual environment at all and the environment variables you set in your virtualenv will be there.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .