Jupyter 简明教程

IPython - Running and Editing Python Script

在本章中,让我们了解如何运行和编辑 Python 脚本。

In this chapter, let us understand how to run and edit a Python script.

Run Command

您可以在输入提示中使用 run 命令运行 Python 脚本。run 命令实际上是行 magic 命令,实际上应该写成 %run 。但是, %automagic 模式始终默认打开,因此您可以省略它。

You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this.

In [1]: run hello.py
Hello IPython

Edit Command

IPython 还提供编辑 magic 命令。它调用操作系统的默认编辑器。您可以通过 Windows 记事本编辑器将其打开并编辑该脚本。在保存其输入后关闭它之后,将显示已修改脚本的输出。

IPython also provides edit magic command. It invokes default editor of the operating system. You can open it through Windows Notepad editor and the script can be edited. Once you close it after saving its input, the output of modified script will be displayed.

In [2]: edit hello.py
Editing... done. Executing edited code...
Hello IPython
welcome to interactive computing

请注意,hello.py 最初仅包含一个语句,在编辑后又添加了一个语句。如果未向编辑命令提供文件名,则会创建一个临时文件。观察以下显示相同内容的代码。

Note that hello.py initially contained only one statement and after editing one more statement was added. If no file name is given to edit command, a temporary file is created. Observe the following code that shows the same.

In [7]: edit
IPython will make a temporary file named:
C:\Users\acer\AppData\Local\Temp\ipython_edit_4aa4vx8f\ipython_edit_t7i6s_er.py
Editing... done. Executing edited code...
magic of IPython
Out[7]: 'print ("magic of IPython")'