How to execute a Python file in Python shell?

PythonServer Side ProgrammingProgramming

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
raja
Published on 27-Dec-2017 10:57:47
Advertisements