You can change environment variable only for current process or its children. To change environment in its parent process would require hacks e.g., using gdb.
In your example export variable=10
is run in the same process and python -c ..
command is a child process (of the shell). Therefore it works.
In your Python example, you are trying (incorrectly) to export variable in a child process and get it in a parent process.
To summarize:
- working example: parent sets environment variable for a child
- non-working example: child tries to set environment variable for a parent
To reproduce your bash example:
import os
import sys
from subprocess import check_call
#NOTE: it works but you shouldn't do it, there are most probably better ways
os.environ['variable'] = '10' # set it for current processes and its children
check_call([sys.executable or 'python', '-c',
'import os; print(os.getenv("variable"))'])
Subprocess either inherits parent's environment or you could set it explicitly using env
argument.
For example, to change a local timezone that is used by time
module, you could change TZ
environment variable for the current python process on posix systems:
import os
import time
os.environ['TZ'] = ':America/New_York'
time.tzset()
is_dst = time.daylight and time.localtime().tm_isdst > 0
# local time = utc time + utc offset
utc_offset = -time.timezone if not is_dst else -time.altzone
print("%s has utc offset: %.1f hours" % (
os.environ.get('TZ').lstrip(':'), utc_offset/3600.))