I wanted to script a python file like a .m file in MATLAB and tried to find out
Condition: IPython (Jupyter Notebook, etc.)
In the folder with "test.py"
%run -i test.py
Allows execution with the "test.py" script.
The namespace will be the same as the main one. It is also possible to put it in for.
In the folder with "test.py"
with open('test.py', 'r', encoding='utf-8') as f:
script = f.read()#Read the script file as a string
exec(script) #Execute string with exec
Can be executed by the script of "test.py"
Normally, when import is used as a module from another file, global variables are different for each file, so it seems that it will not be a pure script. It should be used only for personal experiments, as the namespace spans different files and readability deteriorates.
Recommended Posts