Nesting scripts -- runfile to call a script within a script gives KeyError: '__file__' , but run as a selection works fine
See original GitHub issueIs there a limitation or a technique needed for nesting scripts in Spyder? Carlos Córdoba asked me to put this into the issues tracker. Here are the nested scripts and symptoms of the problem:
Script1.py is: print ("hello")
Script2.py is: runfile ('Script1.py')
Description of problem: F9 key runs this line of code fine, the text hello prints out without an error
F5 key or another script such as Script3.py: runfile (‘Script2.py’) gives an error message after printing hello:
Output error:
hello
Traceback (most recent call last):
File "<ipython-input-24-c314cb3c22a8>", line 1, in <module>
runfile('C:\\Users\\Peter\\Documents\\Roparju Regression\\Accudata\\Base\\Code\\TESTING Step.py')
File "C:\Users\Peter\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 714, in runfile
namespace.pop('__file__')
KeyError: '__file__'
Comments:
Partial work-around seems to work sometimes but not others, but did get me around may hang-up: try-except works as a selection run (F9) but not as a module run (F5)
try:
runfile('C:\\Users\\Peter\\Documents\\Roparju Regression\\Accudata\\Base\\Code\\TEST_functions.py')
except:
print(" ")
I recognize that the pythonic way to call modules is using main and init, but it seems to me runfile should be a viable alternative to that within spyder.
My application has 4 modules called in sequence by a single driver. So, I run the driver to run the 4 modules when I want. But, I also have the option to run (and re-run) the individual modules for testing purposes. Importantly, to run independently, all 4 modules, in turn, need to run a core services module that defines a general set of functions used throughout the application.
I am interested in the better, more pythonic way to code what’s below as long as I have the flexibility to run all, or just a sub-module stand-along (that is, “file read” and “core functions” should be executable):
runfile("driver.py")
runfile("file read")
runfile("core functions")
runfile("data recoding")
runfile("core functions")
runfile("model build")
runfile("core functions")
runfile("model scoring")
runfile("core functions")
Versions:
python 3.6.1
ipython 6.2.1
conda 4.3.31
spyder 3.2.4
Issue Analytics
- State:
- Created 6 years ago
- Comments:15 (8 by maintainers)
Top GitHub Comments
appreciate that tip! @CAM-Gerlach
I guess not.
runfile
is not meant to be used outside of Spyder and in source code.