如何将文件加载到 python 控制台? [英] How do I load a file into the python console?

查看:45
本文介绍了如何将文件加载到 python 控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 python 代码行,我不断将它们复制/粘贴到 python 控制台中.是否有 load 命令或我可以运行的命令?例如加载文件.py

I have some lines of python code that I'm continuously copying/pasting into the python console. Is there a load command or something I can run? e.g. load file.py

推荐答案

对于 Python 2 给 execfile 试试.(请参阅 Python 3 的其他答案)

For Python 2 give execfile a try. (See other answers for Python 3)

execfile('file.py')

示例用法:
让我们使用copy con"快速创建一个小脚本文件...

Example usage:
Let's use "copy con" to quickly create a small script file...

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

...然后让我们像这样加载这个脚本:

...and then let's load this script like so:

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 控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆