Passing a variable to environment

2019-09-06 02:10发布

问题:

I am sorry if my question not very clear.

I am trying to create a variable pass it to the environment in linux. Then, I want to be able to get this variable some where else. What i have tried so far on the linux command line:

local_pc:~/home$ export variable=10
local_pc:~/home$ python -c 'import os; print os.getenv("variable")'
10

which all sound fine. But when I set export in python I will not be able to get it

subprocess.call(["export","variable=20"],shell = True)
print(os.getenv("variable"))
None

So my question here is how to do xport variable=10 in python

回答1:

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.))


回答2:

update:

There's no feasible way to establish commuication over processes through environment variables.

The child may inherit the environment variables from the parent, but a change to the parent environment variables after the childs invocation won't be passed through to the child and the child's environment changes are completely intransparent to the parent. So no way!

I tested it by trying to establish a round-robin, token-based message passing approach, but i don't see a way to get the changes passed between the process environment variables.