Python 简明教程
Python Interpreter and Its Modes
Python Interpreter
Python 是一种基于解释器的语言。在 Linux 系统中,Python 的可执行文件安装在 /usr/bin/ 目录中。对于 Windows,可执行文件 (python.exe) 位于安装文件夹中(例如 C:\python311 )。
Python is an interpreter-based language. In a Linux system, Python’s executable is installed in /usr/bin/ directory. For Windows, the executable (python.exe) is found in the installation folder (for example C:\python311).
本教程将在交互式和脚本模式下教你 How Python Interpreter Works 。Python 代码一次执行一个语句方法。Python 解释器有两种组件。转换器检查语句的语法。如果发现正确,它将生成中间字节码。有一个 Python 虚拟机,它将字节码转换为本机二进制文件并执行它。下图说明了该机制:
This tutorial will teach you How Python Interpreter Works in interactive and scripted mode. Python code is executed by one statement at a time method. Python interpreter has two components. The translator checks the statement for syntax. If found correct, it generates an intermediate byte code. There is a Python virtual machine which then converts the byte code in native binary and executes it. The following diagram illustrates the mechanism:
Python 解释器具有交互模式和脚本模式。
Python interpreter has an interactive mode and a scripted mode.
Python Interpreter - Interactive Mode
当从命令行终端启动且没有任何其他选项时,将出现 Python 提示符 >>> ,并且 Python 解释器将基于 REPL (Read, Evaluate, Print, Loop) 的原理工作。在 Python 提示符前输入的每个命令都会被读取、翻译并执行。典型的交互式会话如下。
When launched from a command line terminal without any additional options, a Python prompt >>> appears and the Python interpreter works on the principle of REPL (Read, Evaluate, Print, Loop). Each command entered in front of the Python prompt is read, translated and executed. A typical interactive session is as follows.
>>> price = 100
>>> qty = 5
>>> total = price*qty
>>> total
500
>>> print ("Total = ", total)
Total = 500
若要关闭交互式会话,请输入行结束字符(对于 Linux 为 ctrl+D,对于 Windows 为 ctrl+Z)。您还可以在 Python 提示符前键入 quit() 并按 Enter 返回到操作系统提示符。
To close the interactive session, enter the end-of-line character (ctrl+D for Linux and ctrl+Z for Windows). You may also type quit() in front of the Python prompt and press Enter to return to the OS prompt.
>>> quit()
$
标准 Python 发行版附带的交互式外壳没有行编辑、历史搜索、自动完成等功能。你可以使用其他高级交互式解释器软件,如 IPython 和 bpython ,以获得其他功能。
The interactive shell available with standard Python distribution is not equipped with features like line editing, history search, auto-completion etc. You can use other advanced interactive interpreter software such as IPython and bpython to have additional functionalities.
Python Interpreter - Scripting Mode
无需像在交互式环境中那样一次输入并获取一条指令的结果,而是可以将一组指令保存在文本文件中,确保它有 .py 扩展名,并将名称用作 Python 命令的命令行参数。
Instead of entering and obtaining the result of one instruction at a time as in the interactive environment, it is possible to save a set of instructions in a text file, make sure that it has .py extension, and use the name as the command line parameter for Python command.
使用任何文本编辑器(如 Linux 上的 vim 或 Windows 上的记事本)将以下行保存为 prog.py 。
Save the following lines as prog.py, with the use of any text editor such as vim on Linux or Notepad on Windows.
print ("My first program")
price = 100
qty = 5
total = price*qty
print ("Total = ", total)
当我们在 Windows 机器上执行上面的程序时,它将产生以下结果:
When we execute above program on a Windows machine, it will produce following result:
C:\Users\Acer>python prog.py
My first program
Total = 500
请注意,即使 Python 一次执行整个脚本,但它在内部仍然按行执行。
Note that even though Python executes the entire script in one go, but internally it is still executed in line by line fashion.
对于任何基于编译器的语言(如 Java),除非整个代码没有错误,否则不会将源代码转换为字节代码。另一方面,在 Python 中,语句执行直到遇到第一个错误。
In case of any compiler-based language such as Java, the source code is not converted in byte code unless the entire code is error-free. In Python, on the other hand, statements are executed until first occurrence of error is encountered.
让我们有目的地在上述代码中引入一个错误。
Let us introduce an error purposefully in the above code.
print ("My first program")
price = 100
qty = 5
total = prive*qty #Error in this statement
print ("Total = ", total)
请注意,拼写错误的变量 prive ,而不是 price 。尝试像以前一样再次执行脚本 −
Note the misspelt variable prive instead of price. Try to execute the script again as before −
C:\Users\Acer>python prog.py
My first program
Traceback (most recent call last):
File "C:\Python311\prog.py", line 4, in <module>
total = prive*qty
^^^^^
NameError: name 'prive' is not defined. Did you mean: 'price'?
请注意,错误语句之前的语句已执行,然后出现错误消息。因此,现在很明显 Python 脚本是以解释的方式执行的。
Note that the statements before the erroneous statement are executed and then the error message appears. Thus it is now clear that Python script is executed in interpreted manner.
Python Interpreter - Using Shebang
除了如上执行 Python 脚本外,该脚本本身还可以在 Linux 中作为自执行文件,就像 shell 脚本一样。您必须在脚本的顶部添加 shebang 行。shebang 指示使用哪个可执行文件解释脚本中的 Python 语句。脚本的第一行以 #! 开头,然后紧跟着 Python 可执行文件的路径。
In addition to executing the Python script as above, the script itself can be a selfexecutable in Linux, like a shell script. You have to add a shebang line on top of the script. The shebang indicates which executable is used to interpret Python statements in the script. Very first line of the script starts with #! And followed by the path to Python executable.
将 prog.py 脚本修改如下 −
Modify the prog.py script as follows −
#! /usr/bin/python3.11
print ("My first program")
price = 100
qty = 5
total = price*qty
print ("Total = ", total)
若要将脚本标记为自执行,请使用 chmod 命令
To mark the script as self-executable, use the chmod command
$ chmod +x prog.py
现在,您可以直接执行脚本,而无需将其用作命令行参数。
You can now execute the script directly, without using it as a command-line argument.
$ ./hello.py
Interactive Python - IPython
IPython(代表 Interactive Python )是 Python 的增强和强大的交互式环境,与标准 Python 外壳相比具有许多功能。IPython 最初于 2001 年由 Fernando Perez 开发。
IPython (stands for Interactive Python) is an enhanced and powerful interactive environment for Python with many functionalities compared to the standard Python shell. IPython was originally developed by Fernando Perez in 2001.
IPython 具有以下重要特性 −
IPython has the following important features −
-
IPython's object introspection ability to check properties of an object during runtime.
-
Its syntax highlighting proves to be useful in identifying the language elements such as keywords, variables etc.
-
The history of interactions is internally stored and can be reproduced.
-
Tab completion of keywords, variables and function names is one of the most important features.
-
IPython’s Magic command system is useful for controlling Python environment and performing OS tasks.
-
It is the main kernel for Jupyter notebook and other front-end tools of Project Jupyter.
使用 PIP 安装程序实用程序安装 IPython。
Install IPython with PIP installer utility.
pip3 install ipython
从命令行启动 IPython
Launch IPython from command-line
C:\Users\Acer>ipython
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:
与标准解释器中的常规 >>> 提示不同,您将注意到两个主要的 IPython 提示,如下所示 −
Instead of the regular >>> prompt as in standard interpreter, you will notice two major IPython prompts as explained below −
-
In[1] appears before any input expression.
-
Out[1]appears before the Output appears.
In [1]: price = 100
In [2]: quantity = 5
In [3]: total = price*quantity
In [4]: total
Out[4]: 500
In [5]:
选项卡补全功能是 IPython 提供的最有用的增强功能之一。在对象前面的句点后面按 Tab 键时,IPython 会弹出适当的方法列表。
Tab completion is one of the most useful enhancements provided by IPython. IPython pops up appropriate list of methods as you press tab key after dot in front of object.
IPython 通过在前面放置 ? 来提供任何对象的详细信息(自省)。它包括 docstring 、函数定义和类的构造函数详细信息。例如,要浏览上面定义的字符串对象 var,在输入提示符中输入 var?。
IPython provides information (introspection) of any object by putting ? in front of it. It includes docstring, function definitions and constructor details of class. For example to explore the string object var defined above, in the input prompt enter var?.
In [5]: var = "Hello World"
In [6]: var?
Type: str
String form: Hello World
Length: 11
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
IPython 的神奇功能功能极其强大。行魔术函数允许您在 IPython 中运行 DOS 命令。让我们从 IPython 控制台中运行 dir 命令
IPython’s magic functions are extremely powerful. Line magics let you run DOS commands inside IPython. Let us run the dir command from within IPython console
In [8]: !dir *.exe
Volume in drive F has no label.
Volume Serial Number is E20D-C4B9
Directory of F:\Python311
07-02-2023 16:55 103,192 python.exe
07-02-2023 16:55 101,656 pythonw.exe
2 File(s) 204,848 bytes
0 Dir(s) 105,260,306,432 bytes free
Jupyter 笔记本是 Python、Julia、R 和许多其他编程环境的基于 Web 的界面。对于 Python,它使用 IPython 作为其主要内核。
Jupyter notebook is a web-based interface to programming environments of Python, Julia, R and many others. For Python, it uses IPython as its main kernel.