操作系统。getenv不返回任何值,而是返回正确的值

时间:2021-12-01 11:08:06

I have a complex piece of software I am not able to post, nor do I have a concrete working example. I will try to explain the problem, maybe someone encountered this before.

我有一个复杂的软件,我不能发布,也没有一个具体的工作示例。我会试着解释这个问题,也许有人以前遇到过。

On the LINUX shell I have defined an environment variable:

在LINUX shell中,我定义了一个环境变量:

> export MY_TEST_ENV=4711
> echo $MY_TEST_ENV
> 4711

Within the complex code I want to obtain this variable with

在复杂的代码中,我希望使用这个变量

print os.getenv('MY_TEST_ENV')

which always returns None. If I create a test-script to test this behavior, even with classes in different files, I always get the desired behavior (i.e. os.getenv('MY_TEST_ENV') returns the correct value 4711).

它总是返回None。如果我创建一个测试脚本来测试这种行为,即使是在不同的文件中使用类,我总是会得到所需的行为(例如,os.getenv('MY_TEST_ENV')返回正确的值4711)。

The code is started as 'sudo'.

代码以“sudo”开头。

Any ideas what could be the reason?

有什么原因吗?

1 个解决方案

#1


6  

Most likely the way you invoke the Python process makes you lose the environment. If you export the variable within a running shell and, directly after that, invoke the Python process in question in the same shell, this environment variable should definitely be available to this Python process. To help you debugging this issue: instead of the code in question (print os.getenv('my...')), print the whole environment via print os.environ. From the result you should be able to infer what happened to your environment.

最可能的情况是,您调用Python进程的方式会使您丢失环境。如果在一个正在运行的shell中导出变量,然后直接在同一个shell中调用问题的Python进程,那么这个环境变量肯定可以用于这个Python进程。为了帮助您调试这个问题:不是要调试的代码(打印os.getenv('my…')),而是通过print os. environment打印整个环境。从结果中你应该能够推断出你的环境发生了什么。

#1


6  

Most likely the way you invoke the Python process makes you lose the environment. If you export the variable within a running shell and, directly after that, invoke the Python process in question in the same shell, this environment variable should definitely be available to this Python process. To help you debugging this issue: instead of the code in question (print os.getenv('my...')), print the whole environment via print os.environ. From the result you should be able to infer what happened to your environment.

最可能的情况是,您调用Python进程的方式会使您丢失环境。如果在一个正在运行的shell中导出变量,然后直接在同一个shell中调用问题的Python进程,那么这个环境变量肯定可以用于这个Python进程。为了帮助您调试这个问题:不是要调试的代码(打印os.getenv('my…')),而是通过print os. environment打印整个环境。从结果中你应该能够推断出你的环境发生了什么。