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

其他-如何在 Python 解释器中执行文件?

(其他 - How to execute a file within the Python interpreter?)

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

我正在尝试从解释器中使用 Python 命令执行文件。

编辑:我正在尝试使用该文件中的变量和设置,而不是调用单独的进程。

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

几种方式。

从外壳

python someFile.py

从 IDLE 内部,点击F5

如果你以交互方式输入,请尝试以下操作:(仅限 Python 2!)

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

对于 Python3,请使用:

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