Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...