我有一个要求,其中 1 个进程将一个值设置为环境变量,并且我使用
在 python 中读取该值os.environ
根据 python 文档:
This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.
我的问题是进程每次调用 python 脚本时都会设置/更改变量。
请告诉我一种读取更改值的方法。
谢谢
最佳答案
我想您可以随时使用 os.getenv() 来获取环境变量的值,这将反射(reflect)最新的状态。
更新:请注意,不存在所谓的“全局”环境,至少在 Linux 上不存在。引用维基百科:
In all Unix and Unix-like systems, each process has its own private set of environment variables. By default, when a process is created it inherits a duplicate environment of its parent process, except for explicit changes made by the parent when it creates the child.
因此,如果您从同一父进程(例如 bash
)启动( fork )两个进程,并更改其中一个进程中的环境变量,则另一个进程将看不到它因为它使用父进程环境的另一个副本。同样,如果您在启动子进程后更改父进程中的环境,子进程将不会看到更改,因为它们已经创建了环境的私有(private)副本。
关于python - 在 Python 中获取更改的环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5935404/