How to execute a Python file in Python shell?


To execute a Python file in the python shell, you could use either the execfile method or the exec method.

Example

For example, you want to run a script called my_script.py that only contains the line:

print("Greetings from my_script")

from the python shell, you could simply enter:

>>> execfile('my_script.py')
Greetings from my_script

Or you could use the exec method as follows:

>>> exec(open("my_script.py").read())
Greetings from my_script

Advertisements