如何将文件加载到python控制台?

时间:2011-03-12 01:26:11

标签: python read-eval-print-loop

我有一些python代码行,我不断复制/粘贴到python控制台。是否有load命令或我能运行的东西?例如load file.py

8 个答案:

答案 0 :(得分:188)

对于Python 2(参见Python 3的其他答案),试一试:

execfile('file.py')

使用示例:

C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
        1 file(s) copied.

C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>

答案 1 :(得分:133)

从手册页:

  

-i当脚本作为第一个参数传递或使用-c选项时,请在执行脚本或命令后进入交互模式。它不会读取$ PYTHONSTARTUP文件。当脚本引发异常时,这对于检查全局变量或堆栈跟踪非常有用。

所以这应该做你想要的:

python -i file.py

答案 2 :(得分:69)

Python 3:新的exec (execfile已删除)

execfile解决方案仅对Python 2有效.Python 3删除了execfile函数 - 并将exec语句提升为内置通用函数。正如Python 3.0的更改日志和Hi-Angels评论中的评论所暗示的那样:

使用

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

而不是

execfile(<filename.py>)

答案 3 :(得分:20)

从shell命令行:

python file.py

从Python命令行

import file

from file import *

答案 4 :(得分:10)

您可以使用import语句:

from file import *

因此,例如,如果你有一个名为my_script.py的文件,你就像这样加载它:

from my_script import *

答案 5 :(得分:3)

如果您正在使用IPython,则只需运行:

%load path/to/your/file.py

请参阅http://ipython.org/ipython-doc/rel-1.1.0/interactive/tutorial.html

答案 6 :(得分:2)

在要导入文件的文件夹中打开命令提示符。当你输入'python'时,将打开python终端。现在您可以使用

import script_name
注意:导入时不使用.py扩展名。
How can I open a cmd window in a specific location?

答案 7 :(得分:0)

如果您的path环境变量包含Python(例如C:\Python27\),则只需从Windows命令行(cmd)运行py文件即可。 Howto here.