如何使用在解释器中创建的python文件?

如何使用在解释器中创建的python文件?,python,Python,有没有办法将我在编辑器中创建的python文件导入解释器进行测试?当然。假设您有script.py,它有函数foo()。转到适当的目录,通过运行python启动IDLE >>> import script >>> script.foo() 顺便说一句,我更喜欢IPython作为我的空闲选择。在本例中,如果您键入“script”,它将显示所有可用选项,然后键入tab。IPython强烈模拟空闲时的命令行行为(例如运行ls)。如果要启动Python控制台并执行文

有没有办法将我在编辑器中创建的python文件导入解释器进行测试?

当然。假设您有script.py,它有函数foo()。转到适当的目录,通过运行python启动IDLE

>>> import script
>>> script.foo()

顺便说一句,我更喜欢IPython作为我的空闲选择。在本例中,如果您键入“script”,它将显示所有可用选项,然后键入tab。IPython强烈模拟空闲时的命令行行为(例如运行ls)。

如果要启动Python控制台并执行文件,以便其变量对您可用,请使用
-i

$ cat foo.py
a = [1,2,3]
b = 42
print('Hello world')
$ python -i foo.py
Hello world
>>> a
[1, 2, 3]
>>> b
42
>>> quit()
如果您已经在解释器中,请使用
execfile
,如下所示:

$ python
Python 2.7.6 (default, Apr  9 2014, 11:48:52)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('foo.py')
Hello world
>>> a
[1, 2, 3]
>>> b
42
>>> from foo import a,b
Hello world
>>> a
[1, 2, 3]
>>> b
42
如果您只想使用文件中的某个变量,请使用
import
,如下所示:

$ python
Python 2.7.6 (default, Apr  9 2014, 11:48:52)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('foo.py')
Hello world
>>> a
[1, 2, 3]
>>> b
42
>>> from foo import a,b
Hello world
>>> a
[1, 2, 3]
>>> b
42
请注意,这将执行该文件,这就是为什么您会看到打印的
Hello world