Importing A Variable From Another Script And Keeping It Updated
Solution 1:
There is a way to reload modules, though it doesn't seem to work well with aliasing. You can use reload(module_name)
. As you'll see the docs note that your aliases wont be refreshed:
If a module imports objects from another module using
from ... import ...
, callingreload()
for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*
) instead.
It instead suggests using
import script2
script2.variable1
You could still alias, but you'd need to refresh the aliased names each time:
importscript2var1= script2.variable1
...
reload(script2)
var1 = script2.variable1
If you didn't do this, var1
would hold the old value.
You could however have a quick function to do this all at once if you think it's necessary (and if it is happening often)
def reload_script2():
global var1
reload(script2)
var1 = script2.variable1
Note I use global
here so that var1
is modified in the global namespace, not just declared in that function. If you really only have one value you could use return var1
, but I think this is a rare case where global
is better.
Solution 2:
For ipython, use the %load
magic command:
In [1]: from a import x
In [2]: x
Out[2]: 20# here go and change the content of a.py
In [3]: from a import x
In [4]: x
Out[4]: 20# same value
In [5]: %load a.py
In [6]: # %load a.py
x = 22
In [7]: x
Out[7]: 22# new value
Solution 3:
If you have to change the variables often I think its not a good approach to write it to a python script but rather to a config file. There you could simple read it like this
def getVar(name):
c = ConfigParser.SafeConfigParser()
c.read('config.cfg')
return c.get('global',name)
While the variable is written in your config.cfg
file like this:
[global]var1 = 5var2 = 10
You could also save it as JSON and just use a json reader instead of the config reader.
In the end you can get your variable with getVar('var1')
and it will always be up to date.
Solution 4:
It would be easier just to store the value in a file. For example, in the first script you would have:
myvar = 6
# do stuff
config_file = open('config.txt', 'w')
config_file.write(myvar)
config_file.close()
and in the second script you would have:
config_file_read = open('config.txt', 'r')
oldvar = int(config_file_read.read()) # you could also do float() (or any type)
config_file_read.close()
print oldvar
newvar = 5
config_file_write = open('config.txt', 'w') # this overwrites the contents of the file
config_file_write.write(str(newvar))
config_file_write.close()
Post a Comment for "Importing A Variable From Another Script And Keeping It Updated"