Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change environment variables before importlib.reload

I have a c-extension that loads environment variables during static initialization. I need to be able to change these values and reload the module (I cannot change the fact that they are loaded statically). I tried setting os.environ, but there doesn't seem to be an env option in importlib like for subprocess.call

Here's an example: suppose I have a module defined as follows

#include <boost/python.hpp>
#include <cstdlib>
#include <string>
std::string get() {
    return ::getenv("HOME");
}

BOOST_PYTHON_MODULE(sample) {
    boost::python::def("get", &get);
}

And I have python code:

import importlib, os
import sample as s
print(s.get()) # prints /home/username

# do something like 
# os.environ['HOME'] = 'foo'
importlib.reload(s)
print(s.get()) # I would like this to print 'foo'

In other words, what can I do instead of os.environ['HOME'] = 'foo' to cause the environment variable to change in the c-module?

NOTE: I cannot use setenv because the variables are loaded statically and I am unable to reinitializes all the things that depend on them.

like image 438
JRG Avatar asked Mar 13 '17 15:03

JRG


People also ask

What is the use reload() in Python?

The reload() is used to reload a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have made changes to the code.

How do you force reimport in Python?

1 Answer. You can re-import a module in python, by using the importlib and its function reload.

Where are .ENV files stored?

The Global environment variables of your system are stored in /etc/environment . Any changes here will get reflected throughout the system and will affect all users of the system. Also, you need a Reboot, for any changes made here to take effect.


1 Answers

If I am not mistaken, the reason this does not work is not because the environment is not modified but because when you do importlib.reload(s) the c module is not actually re-initialized.

What you can do is put your calls to s in another process, and whenever you need to reload it create a new process.

like image 79
Giannis Spiliopoulos Avatar answered Oct 05 '22 00:10

Giannis Spiliopoulos