简体   繁体   English

Linux上的Python中的环境变量

[英]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. Python对环境变量的访问不能准确反映操作系统对进程环境的看法。

os.getenv and os.environ do not function as expected in particular cases. os.getenv和os.environ在特定情况下无法正常运行。

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): 为了演示我的意思,请使用两个大致等效的程序(第一个在C中,另一个在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: 现在,如果我们运行C程序并使用gdb附加到正在运行的进程,并通过执行以下操作来强行更改内部环境:

(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. 那么上述C程序将每5秒钟喷出一次“我的值”。 The aforementioned python program, however, will not. 但是,上述python程序不会。

Is there a way to get the python program to function like the C program in this case? 在这种情况下,有没有办法让python程序像C程序一样起作用?

(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. 另外,我当前正在使用python 2.4,这可能已在更高版本的python中修复。

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. 事实证明, os模块将os.environ初始化为posix .environ的值,该值是在解释器启动时设置的。 In other words, the standard library does not appear to provide access to the getenv function. 换句话说,标准库似乎没有提供对getenv函数的访问。

That is a case where it would probably be safe to use ctypes on unix. 在这种情况下,在unix上使用ctypes可能是安全的。 Since you would be calling an ultra-standard libc function. 因为您将调用超标准的libc函数。

You can use ctypes to do this pretty simply: 您可以使用ctypes非常简单地执行此操作:

>>> from ctypes import CDLL, c_char_p
>>> getenv = CDLL("libc.so.6").getenv
>>> getenv.restype = c_char_p
>>> getenv("HOME")
'/home/glyph'

Another possibility is to use pdb, or some other python debugger instead, and change os.environ at the python level, rather than the C level. 另一种可能性是改用pdb或其他一些python调试器,并在python级别而不是C级别更改os.environ。 Here's a small recipe I posted to interrupt a running python process and provide access to a python console on receiving a signal. 这是我发布一个小食谱,用于中断正在运行的python进程,并在接收到信号后提供对python控制台的访问。 Alternatively, just stick a pdb.set_trace() at some point in your code you want to interrupt. 或者,只需将pdb.set_trace()粘贴在您要中断的代码中的某个位置即可。 In either case, just run the statement " import os; os.environ['SOME_VARIABLE']='my_value' " and you should be updated as far as python is concerned. 无论哪种情况,只要运行语句“ import os; os.environ['SOME_VARIABLE']='my_value' ”,就python而言,您应该进行更新。

I'm not sure if this will also update the C environment with setenv, so if you have C modules using getenv directly you may have to do some more work to keep this in sync. 我不确定这是否还会使用setenv更新C环境,因此,如果您直接使用getenv使用C模块,则可能需要做更多工作才能保持同步。

I don't believe many programs EVER expect to have their environment externally modified, so loading a copy of the passed environment at startup is equivalent. 我不相信许多程序会期望从外部修改其环境,因此在启动时加载传递的环境的副本是等效的。 You have simply stumbled on an implementation choice. 您只是偶然发现了一个实现选择。

If you are seeing all the set-at-startup values and putenv/setenv from within your program works, I don't think there's anything to be concerned about. 如果您在程序中看到所有启动时设置的值和putenv / setenv,我认为没有什么可担心的。 There are far cleaner ways to pass updated information to running executables. 有更干净的方法将更新的信息传递给正在运行的可执行文件。

Looking at the Python source code (2.4.5): 查看Python源代码(2.4.5):

  • Modules/posixmodule.c gets the environ in convertenviron() which gets run at startup (see INITFUNC) and stores the environment in a platform-specific module (nt, os2, or posix) Modules / posixmodule.c在convertenviron()中获取环境,该环境在启动时运行(请参阅INITFUNC),并将环境存储在特定于平台的模块(nt,os2或posix)中

  • Lib/os.py looks at sys.builtin_module_names, and imports all symbols from either posix, nt, or os2 lib / os.py查看sys.builtin_module_names,并从posix,nt或os2导入所有符号

So yes, it gets decided at startup. 是的,它在启动时就决定了。 os.environ is not going to be helpful here. os.environ在这里不会有帮助。

If you really want to do this, then the most obvious approach that comes to mind is to create your own custom C-based python module, with a getenv that always invokes the system call. 如果您真的想这样做,那么想到的最明显的方法是创建一个自己的基于C的自定义python模块,并使用一个getenv始终调用系统调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM