【问题标题】:Rerun python program from terminal after making changes进行更改后从终端重新运行 python 程序
【发布时间】:2016-02-16 18:45:06
【问题描述】:

从命令行运行 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 代码进行更改时一遍又一遍地完成所有工作?

【问题讨论】:

标签: python command-line


【解决方案1】:

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

$ python my_tests.py

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

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

【讨论】:

    【解决方案2】:

    将 IPython 与 notebook 一起使用。更适合交互式计算。

    【讨论】:

      【解决方案3】:

      也选择 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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-02
        • 2020-07-08
        • 2012-02-20
        • 2015-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        相关资源
        最近更新 更多