如何在pythonsh中每次按enter键时运行函数

2024-04-19 15:42:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有时在交互式shell中编写小函数。在

它们很少第一次是正确的,所以我花了很多时间在同一个测试集中运行函数的版本来验证正确性。在

>>> def test_foo():
        print( foo(4) == 5 )
        print( foo(8) == 9 )
>>> def foo(x): return x + 1
>>> test_foo()
True
True

但是foo可能更复杂,我可能需要5次或更多的重写才能通过测试,因为手动运行套件很无聊,我需要这样的东西:

^{pr2}$

现在每次我重写foo函数并将其发送到定义时,测试也将运行。在

一些研究

  • 搜索谷歌没有给出有用的答案。在
  • 在shell中,python -h没有告诉我如何做到这一点。在
  • 'ipython中,%quickref也没有。在

Tags: 函数test版本truereturn定义foo套件
3条回答

因为您使用的是ipython,所以您只需创建一个whatever.py文件,其中包含启动时要运行的代码,然后通过ipython whatever.py运行ipython。在

也可以通过modifying your ^{}运行Python代码:

There should be a simple template ipy_user_conf.py file in your ~/.ipython directory. It is a plain python module that is imported during IPython startup, so you can do pretty much what you want there - import modules, configure extensions, change options, define magic commands, put variables and functions in the IPython namespace, etc. You use the IPython extension api object, acquired by IPython.ipapi.get() and documented in the "IPython extension API" chapter, to interact with IPython.

您还可以将a file called ^{}放在当前工作目录中:

As we've already mentioned, IPython reads a configuration file which can be specified at the command line (-rcfile) or which by default is assumed to be called ipythonrc. Such a file is looked for in the current directory where IPython is started and then in your IPYTHONDIR, which allows you to have local configuration files for specific projects. In this section we will call these types of configuration files simply rcfiles (short for resource configuration file).

execute : give any single-line python code to be executed.

execfile : execute the python file given with an execfile(filename) command. Username expansion is performed on the given names. So if you need any amount of extra fancy customization that won't fit in any of the above 'canned' options, you can just put it in a separate python file and execute it.

为此,我强烈建议使用Jupyter notebooks(以前称为IPython)。它允许您创建一个“cell”,其中包含可以用Ctrl-Enter组合键重新执行的代码。在

你可以很容易地在你的例子中,重新执行你的定义。在

Jupyter notebook interface

通过这种方式,您可以逐步构建代码,一次修复和开发单个函数。在

由于您已经安装了IPython,因此您应该能够安装并运行:

$ pip install jupyter
$ jupyter notebook

它将在您的浏览器中启动。通过单击右上角的“新建”并在“笔记本”下选择一个Python内核来创建一个新的笔记本。在

您可以在编辑器中编辑代码,并使用文件监视程序在终端中运行测试,这样每次保存代码或测试文件时都会运行测试。在

有关如何在文件更改时运行命令(文件监视程序)的信息,请参阅有关此问题的答案:https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes

相关问题 更多 >