我有一些 python 代码行,我不断地将它们复制/粘贴到 python 控制台中。有load
命令或我可以运行的东西吗?例如load file.py
8 回答
从手册页:
-i 当脚本作为第一个参数传递或使用 -c 选项时,在执行脚本或命令后进入交互模式。它不读取 $PYTHONSTARTUP 文件。当脚本引发异常时,这对于检查全局变量或堆栈跟踪很有用。
所以这应该做你想要的:
python -i file.py
对于 Python 2execfile
试一试。(请参阅 Python 3 的其他答案)
execfile('file.py')
用法示例:
让我们使用“copy con”快速创建一个小脚本文件...
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
>>>
Python 3:新的 exec (删除了 execfile) !
execfile 解决方案仅对 Python 2 有效。Python 3 删除了 execfile 函数 - 并将 exec 语句提升为内置通用函数。正如 Python 3.0 的更新日志和 Hi-Angels 评论中的评论所暗示的:
利用
exec(open(<filename.py>).read())
代替
execfile(<filename.py>)
从 shell 命令行:
python file.py
从 Python 命令行
import file
或者
from file import *
您可以只使用导入语句:
from file import *
因此,例如,如果您有一个名为的文件,my_script.py
您会像这样加载它:
from my_script import *
在您要导入的文件所在的文件夹中打开命令提示符。当你输入“python”时,python 终端将被打开。现在你可以使用
导入脚本名称注意:导入时不要使用 .py 扩展名。
如何在特定位置打开 cmd 窗口?
如果您使用的是 IPython,您可以简单地运行:
%load path/to/your/file.py
见http://ipython.org/ipython-doc/rel-1.1.0/interactive/tutorial.html
If your path
environment variable contains Python (eg. C:\Python27\
) you can run your py file simply from Windows command line (cmd).
Howto here.