Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment Variables in Python on Linux

Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.

os.getenv and os.environ do not function as expected in particular cases.

Is there a way to properly get the running process' environment?


To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]){
    char *env;
    for(;;){
        env = getenv("SOME_VARIABLE");
        if(env)
            puts(env);
        sleep(5);
    }
}

import os
import time
while True:
    env = os.getenv("SOME_VARIABLE")
    if env is not None:
        print env
    time.sleep(5)

Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:

(gdb) print setenv("SOME_VARIABLE", "my value", 1)
[Switching to Thread -1208600896 (LWP 16163)]
$1 = 0
(gdb) print (char *)getenv("SOME_VARIABLE")
$2 = 0x8293126 "my value"

then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.

Is there a way to get the python program to function like the C program in this case?

(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)

Also, I'm currently using python 2.4, this may have been fixed in a later version of python.

like image 472
Sufian Avatar asked Oct 24 '08 22:10

Sufian


1 Answers

That's a very good question.

It turns out that the os module initializes os.environ to the value of posix.environ, which is set on interpreter start up. In other words, the standard library does not appear to provide access to the getenv function.

That is a case where it would probably be safe to use ctypes on unix. Since you would be calling an ultra-standard libc function.

like image 164
ddaa Avatar answered Sep 21 '22 12:09

ddaa