Nuitka
The Python compiler
Loading...
Searching...
No Matches
HelpersEnvironmentVariables.c
1// Copyright 2025, Kay Hayen, mailto:kay.hayen@gmail.com find license text at end of file
2
3// Helpers for working with environment variables from Python binary in a
4// portable way.
5
6#include "nuitka/environment_variables.h"
7
8#include "HelpersEnvironmentVariablesSystem.c"
9
10void undoEnvironmentVariable(PyThreadState *tstate, char const *variable_name, environment_char_t const *old_value) {
11 PyObject *os_module = IMPORT_HARD_OS();
12 CHECK_OBJECT(os_module);
13
14 PyObject *os_environ = PyObject_GetAttrString(os_module, "environ");
15 CHECK_OBJECT(os_environ);
16
17 PyObject *variable_name_str = Nuitka_String_FromString(variable_name);
18 CHECK_OBJECT(variable_name_str);
19
20 if (old_value) {
21 setEnvironmentVariable(variable_name, old_value);
22
23#ifdef _WIN32
24 PyObject *env_value = NuitkaUnicode_FromWideChar(old_value, -1);
25#else
26 PyObject *env_value = Nuitka_String_FromString(old_value);
27#endif
28 CHECK_OBJECT(env_value);
29
30 int res = PyObject_SetItem(os_environ, variable_name_str, env_value);
31
32 if (unlikely(res != 0)) {
33 PyErr_PrintEx(1);
34 Py_Exit(1);
35 }
36
37 Py_DECREF(env_value);
38 } else {
39 unsetEnvironmentVariable(variable_name);
40
41 int res = PyObject_DelItem(os_environ, variable_name_str);
42
43 if (unlikely(res != 0)) {
44 CLEAR_ERROR_OCCURRED(tstate);
45 }
46 }
47
48 Py_DECREF(variable_name_str);
49 Py_DECREF(os_environ);
50}
51
52// Part of "Nuitka", an optimizing Python compiler that is compatible and
53// integrates with CPython, but also works on its own.
54//
55// Licensed under the Apache License, Version 2.0 (the "License");
56// you may not use this file except in compliance with the License.
57// You may obtain a copy of the License at
58//
59// http://www.apache.org/licenses/LICENSE-2.0
60//
61// Unless required by applicable law or agreed to in writing, software
62// distributed under the License is distributed on an "AS IS" BASIS,
63// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
64// See the License for the specific language governing permissions and
65// limitations under the License.