在进行更改后从终端重新运行python程序

时间:2015-11-15 17:02:00

标签: python command-line

从命令行运行Python非常好且容易。特别是用于测试目的。 唯一的缺点是在对脚本进行更改后,我必须重新启动Python,再次执行所有导入,创建对象并输入参数。

$ python
>>> from foo import bar
>>> from package.file import Class
>>> c = Class
>>> c.name = "John"
>>> c.age = 33
>>> c.function()
>>> from datetime import timedelta, datetime
>>> now = datetime.now().year()
>>> next_year = now + timedelta(year=1)
>>> etc...

有人可以告诉我,如果有更简单的方法,那么每次我在Python代码中进行更改时,一遍又一遍地完成所有工作吗?

3 个答案:

答案 0 :(得分:1)

使用IPython而不是notebook。对交互式计算来说要好得多。

答案 1 :(得分:1)

您可以考虑将测试转换为实际的python脚本。可以像这样运行,然后检查输出

$ python my_tests.py

但是,更好的方法是编写一些可以以类似方式运行的单元测试。 https://docs.python.org/2/library/unittest.html。 unittest框架将运行您定义的所有测试,并将结果收集到报告中。

如果您需要以交互方式完成某些步骤,那么您可以通过将您的设置编写到脚本中,然后在进行交互式测试之前执行脚本来实现这一目标。请参阅此其他问题:Is there a possibility to execute a Python script while being in interactive mode

答案 2 :(得分:0)

也要去IPython。您可以编写一个脚本,该脚本将在任何帧中的任何位置输入交互式shell,例如:

import IPython
from foo import bar
from package.file import Class
c = Class
c.name = "John"
c.age = 33
c.function()
from datetime import timedelta, datetime
now = datetime.now().year()
next_year = now + timedelta(year=1)
IPython.embed()

然后只需用python运行你的脚本,最后你就会获得一个交互式shell。