How to import a module and change the value of a variable inside the module and execute it

I have a module that I need to import and modify certain values โ€‹โ€‹of variables inside an imported instance of this module, and then execute it.

Please note that I cannot make any changes to the imported module due to outdated reasons.

Here is what I am trying to do:

let's say the module I want to import, a.py, looks like

var1 = 1 var2 = 2 if __name__ == '__main__': print var1+var2 

Now I am importing this into b.py calling the script. I am trying to import it, change the value of the var1 variable and run it as the main program using runpy as follows.

 import runpy import a a.var1 = 2 result = runpy._run_module_as_main(a.__name__) 

But this result is output only as 3 , and not as 4 , as expected.

Any other way to achieve this (other than using runpy) without changing anything in a.py? Open any third-party module, since I do not need to make changes to the imported module.

I am using python 2.6

+5
source share
1 answer

Here is a specific implementation of what I suggested in the comments:

 #File temp.py var1 = 1 var2 = 2 if __name__ == '__main__': print var1+var2 

I call it through another run.py file. The key must have another dict class that is immune to any changes to variables that the module can change upon import / start. This dictionary contains the variables whose value you want to change.

 #File: run.py class UpdatedDict(dict): def __setitem__(self, key, value): if key != "var1": super(UpdatedDict, self).__setitem__(key, value) u = UpdatedDict({"var1": 10, '__name__': '__main__'}) exec open("temp.py").read() in u #u here is the globals() for the module. 

Output

 ~/Temp$ python run.py 12 #Yay! 

Note This is a quick and dirty run and is only intended to show you how you can do this. I suggest going through runpy and making this code more reliable. The way it stands now is the correct definition of hacking

+3
source

All Articles