I want to ensure that os.environ
and sys.path
are identical for all ways we start the Python interpreter:
Is there a common way to solve this?
If yes, great: How does it look like?
If no, sad: Everybody solves this on his own. ... What is a good way to solve this?
Operating System: Linux (with systemd support)
Update
More explicit:
sys.path
to be the same in web requests, cron jobs, python started from shell, ...os.environ
to be the same in web requests, cron jobs, python started from shell, ...Update2
For systemd we use EnvironmentFile
Update3
We use virtualenv
You can use envdir python port (here is the original) for managing the environment variables.
If you are only concerned about Django, I suggest using envdir from your settings.py
programmatically
You can update the environment programmatically (e.g.: in the wsgi file, django's manage.py
, settings.py
, etc.)
import envdir
import os
# print os.environ['FOO'] # would raise a KeyError
path = '../envdir/prod'
if not os.path.isdir(path):
raise ValueError('%s is not a dir' % path)
envdir.Env(path)
print os.environ['FOO']
or you can run the your process through envdir
on the command line, e.g.: envdir envs/prod/ python manage.py runserver
I suggest creating aliases for python, pip, etc. (as you don't want to overwrite the system's own python), e.g.: alias python-mycorp="envdir /abs/path/to/envs/prod/ python"
(or if you prefer, write a full shell script instead of an alias).
This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.
They all have to use the same interpreter. If they launch by the same user, they probably are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With