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.

6/22/2009 3:15:54 PM

Accepted Answer

Several ways.

From the shell


From inside IDLE, hit F5.

If you're typing interactively, try this: (Python 2 only!)

>>> variables= {}
>>> execfile( "", variables )
>>> print variables # globals from the someFile module
5/22/2019 8:47:29 PM

For Python 2:

>>> execfile('')

For Python 3:

>>> exec(open("").read())
# or
>>> from pathlib import Path
>>> exec(Path("").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 after executing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow