How to execute a file within the python interpreter?

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.


Several ways.

  • From the shell

    python someFile.py
    
  • From inside IDLE, hit F5.

  • If you're typing interactively, try this (Python3):

    >>> exec(open("filename.py").read())
    
  • For Python 2:

    >>> variables= {}
    >>> execfile( "someFile.py", variables )
    >>> print variables # globals from the someFile module
    

Surprised I haven't seen this yet. You can execute a file and then leave the interpreter open after execution terminates using the -i option:

| foo.py |
----------
testvar = 10

def bar(bing):
  return bing*3

--------



$ python -i foo.py
>>> testvar 
10
>>> bar(6)
18

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).

Python 3 exec Documentation

Tags:

Python