Using /etc/environment in Python virtualenv

2.1k views Asked by At

I am working on a daemon script that starts a bottle app using python-daemon package. The script is /etc/init.d/app.sh

There are some environment variables set in /etc/environment that are to be used in the application's settings.py file (os.environ).

As soon as I activate the virtualenv all the system environment variables are removed (including the ones that I have set in /etc/environment).

The init script I am using is

. /root/webapps/myapp/bin/activate

case "$1" in
    start)
    echo "Starting server"
    # Start the daemon 
    python /root/webapps/myapp/project/index.py start
    ;;
stop)
    echo "Stopping server"
    # Stop the daemon
    python /root/webapps/myapp/project/index.py stop
    ;;
restart)
    echo "Restarting server"
    python /root/webapps/myapp/project/index.py restart
    ;;
*)
    # Refuse to do other stuff
    echo "Usage: /etc/init.d/app {start|stop|restart}"
    exit 1
    ;;
esac

exit 0

Also when I check for the environment variables that I have defined in /etc/environment in ipython shell, variables show up fine. Only when I try to start the application using the init script, everything goes blank.

What I am looking for is a proper method of using variables defined in /etc/environment in my application inside virtualenv.

3

There are 3 answers

4
cronburg On

Try adding the following to the top of your /etc/init.d/app.sh script:

source /etc/environment

Then any and all environment variables set in /etc/environment should be seen by python when you start the application using the init script.

1
Burhan Khalid On

The activate script is nothing special, it just modifies your path. You can achieve the same in your launcher:

. /etc/environment
export PATH=/root/webapps/myapp/bin:$PATH
export VENV_BIN=/root/webapps/myapp/bin
export PROJECT_ROOT=/root/webapps/myapp/project

case "" in
    start)
    echo "Starting server"
    # Start the daemon 
    $VENV_BIN/python $PROJECT_ROOT/index.py start
    ;;
stop)
    echo "Stopping server"
    # Stop the daemon
    $VENV_BIN/python $PROJECT_ROOT/index.py stop
    ;;
restart)
    echo "Restarting server"
    $VENV_BIN/python $PROJECT_ROOT/index.py restart
    ;;
*)
    # Refuse to do other stuff
    echo "Usage: /etc/init.d/app {start|stop|restart}"
    exit 1
    ;;
esac

exit 0
0
Mudasir Mirza On

The link below provides interesting fix. I will be modifying my application to some extent to get it working

https://unix.stackexchange.com/questions/44370/how-to-make-unix-service-see-environment-variables