I'm afraid I don't understand something basic. I use python interactively with IPython and I'm running more or less the following script (VPP is a module I wrote with class VPP and class Forecast, they both extend from object).
import os
import numpy as np
from VPPP import VPP, Forecast
setup = False
single_run = True
if setup:
vpp = VPP(foo=foo, bar=bar, ...)
forecast = Forecast('my_filename')
mapping = {'Forecast': 'PConInput.ys[xxx]', 'Price': 'tariffInput.ys[xxx]'}
if single_run:
fnext = forecast.predict(startday=146, nb_days=2)
vpp.adapt_forecasts(fnext, mapping)
vpp.optimize()
I have the flags setup and single_run because the instantiation of vpp takes about 2 minutes, and I want to use the same vpp later in single run with different parameters.
When I run the script with both flags True, all is fine. However, when I run again with setup = False I get an errormessage: NameError: name 'forecast' is not defined (caused by fnext = ...). However, typing directly in the IPython shell, all instances are known and all commands work fine.
Is this an IPython issue? How can I avoid the instantiation of my vpp object everytime I want to run my script?
Thanks on beforehand for your answers. Roel
Do you run the script using the IPython %run command?
In that case use:
In [#]: %run -i filename.py
-i runs the file in IPython's namespace (instead of an empty one).
For documentation, type %run?<ENTER> in IPython.
Whenever you start a script in Python it starts with a clean 'slate'. No variables are defined yet, there is not some magic memory Python uses to restore variables created in a previous run of the script.
If you want such behavior you will have to store your variables yourself, e.g. using pickle (note this probably won't work if you're communicating with some remote server).
An other solution is to run the script indefinitely and make it do some work every x seconds. Or ask for user input:
import os
import numpy as np
from VPPP import VPP, Forecast
vpp = VPP(foo=foo, bar=bar, ...)
forecast = Forecast('my_filename')
mapping = {'Forecast': 'PConInput.ys[xxx]', 'Price': 'tariffInput.ys[xxx]'}
while True:
try:
raw_input('Press enter to start. Ctrl-C to exit.')
except KeyboardInterrupt:
break
fnext = forecast.predict(startday=146, nb_days=2)
vpp.adapt_forecasts(fnext, mapping)
vpp.optimize()
Now if you press Enter the last three lines will be executed. You can Ctrl-C to exit.
(N.B. for Python 3 change raw_input to input.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With