Categories
Python Answers

How to execute a file within the Python interpreter?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *