How to execute a file within the Python interpreter?

Sometimes, we want to execute a file within the Python interpreter.

In this article, we’ll look at how to execute a file within the Python interpreter.

How to execute a file within the Python interpreter?

To execute a file within the Python interpreter, we can run python with the file name of the file.

In the interactive prompt, we can use exec.

For instance, we run

python filename.py

to run filename.py from the shell.

When we’re in the REPL, we run

exec(open("filename.py").read())

to run filename.py by opening it with open and then call read to read the code.

Then we call exec with the returned code to run it.

Conclusion

To execute a file within the Python interpreter, we can run python with the file name of the file.

In the interactive prompt, we can use exec.