python - 在 Python 中获取更改的环境变量

标签 python

我有一个要求,其中 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/

相关文章:

python - 在Python中根据声音/同音词匹配字符串?

python - 简单的 python Web 服务器在 Windows 10 上被阻止

python - 哪种redis方法比较好 : calling HSET multiple times or calling HMSET once?

python - 在 Django 中反向自引用外键

Python、Tkinter;取消选中复选框时如何使用 grid_forget() ?

python - numpy matmul ('at'/@ 运算符的精度问题)

python - 表情符号模块 Python

python - 通过 SSH 和 SQLAlchemy 将 Python 连接到 Redshift

python - 查找已知哈希值和原始值的hash/crc32算法

python - 在 django-admin 中,如何将 filter_horizo​​ntal 设置为默认值?