Warm tip: This article is reproduced from serverfault.com, please click

How to execute a file within the Python interpreter?

发布于 2009-06-22 15:05:00

I'm trying to execute a file with Python commands from within the interpreter.

EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.

Questioner
Adam Matan
Viewed
11
17.6k 2019-10-02 12:31:47

Several ways.

From the shell

python someFile.py

From inside IDLE, hit F5.

If you're typing interactively, try this: (Python 2 only!)

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

For Python3, use:

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