How to execute a file within the Python interpreter?
I'm trying to execute a file with Python commands from within the interpreter.
EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.
Several ways.
From the shell
python someFile.py
From inside IDLE, hit F5.
If you're typing interactively, try this: (Python 2 only!)
>>> variables= {}
>>> execfile( "someFile.py", variables )
>>> print variables # globals from the someFile module
For Python3, use:
>>> exec(open("filename.py").read())
For Python 2:
>>> execfile('filename.py')
For Python 3:
>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())
See the documentation. If you are using Python 3.0, see this question.
See answer by @S.Lott for an example of how you access globals from filename.py after executing it.