Tutorial

如何使用Python的交互控制台

Published on December 2, 2019
中文
如何使用Python的交互控制台

简介

Python的交互控制台(也叫做Python解释器,或是Python Shell)为程序员提供了"运行指令"和"不创建文件测试测试代码"的快速途径。

交互控制台可以调用所有的Python内置函数和任何已安装的模块、命令行历史、和自动补全。它为"探索Python语言"和"写好代码后粘贴入文件"提供了便利。

这个教程中我们将介绍如何使用Python的交互控制台,以及促使它成为你的得力编程工具。

进入交互控制台

从"本地电脑"或者"安装了Python的服务器"都可以进入Python交互控制台。

进入你默认版本Python交互控制台的常规命令是:

  1. python

如果你已经有设置好的编程环境,你可以进入那个环境,去使用你在那个环境里安装的Python版本和模块。进入环境可以通过以下命令:

  1. cd environments
  2. . my_env/bin/activate

接下来输入Python命令:

  1. python

在这个情况下,默认的Python版本是Python 3.5.2,版本信息在你输入指令之后会自动显示。与版本信息同时显示的还有一些版权信息,以及一些可以获得更多信息的命令:

Output
Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>>

主界面中的下一行将是三个大于号(>>>):

如果你想使用某一特定版本的Python,你可以在Python命令后面直接加上版本号(没有额外的空格):

  1. python2.7
Output
Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>

此处我们得知Python 2.7.2将被使用。如果我们Python2的默认版本是2.7.2, 那么我们可以在命令行里简略成python2

若你想进入Python3,那么应当使用下面的命令:

  1. python3
Output
Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>>

我们同样可以在交互控制台中输入python3.5得到同样的结果。

Python交互控制台在成功运行之后,我们可以继续学习使用Python的Shell环境。

使用Python交互控制台

Python的交互解释器会接收Python的句法,你需要在>>>前缀之后进行输入。

比如,我们可以给变量赋值:

  1. birth_year = 1868

当我们给birth_year这个变量赋值为1868之后,我们按下回车键会得到新的一行,这一行同样会有>>>的前缀:

  1. birth_year = 1868

我们可以继续赋值变量,然后进行数学运算去得到计算结果:

>>> birth_year = 1868
>>> death_year = 1921
>>> age_at_death = death_year - birth_year
>>> print(age_at_death)
53
>>> 

如上脚本所示,我们给变量赋值,用一个变量减去另一个变量,让控制台打印出两者的差值。

正如Python的其他形式一样,你同样可以将控制台直接作为计算器使用:

>>> 203 / 20
10.15
>>> 

此处我们将两个整数20320进行相除,得到结果10.15

多行

当我们想写出多行Python命令式,解释器将有另一个提示符去表示新的连续行,三个点 (...)。

去分开连续的行,你将需要按两次回车键ENTER

我们可以通过下吗的例子去看到这个句法是什么样的。给两个变量赋值,然后用一个条件语句决定在控制台中打印什么:

>>> sammy = 'Sammy'
>>> shark = 'Shark'
>>> if len(sammy) > len(shark):
...     print('Sammy codes in Java.')
... else:
...     print('Sammy codes in Python.')
... 
Sammy codes in Python.
>>> 

在这个例子中两个字符串的长度相等,因此else语句将进行打印。 请注意你需要用"四个连续的空格"去将Python代码进行缩进,否则你将得到以下错误:

>>> if len(sammy) > len(shark):
... print('Sammy codes in Java.')
  File "<stdin>", line 2
    print('Sammy codes in Java.')
        ^
IndentationError: expected an indented block
>>> 

你不但可以在Python控制台中试验多行代码,而且可以导入模块。

导入模块

Python解释器提供快捷的方法能让你去测试一个模块在一个特定的编程环境中是否可用。你可以通过import语句进行测试:

>>> import matplotlib
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'matplotlib'

在上面的例子中,matplotlib模块在当前的编程环境中不可用。

若想安装这个模块,你需要退出交互控制台,然后用pip的常规方法去安装:

  1. pip install matplotlib
Output
Collecting matplotlib Downloading matplotlib-2.0.2-cp35-cp35m-manylinux1_x86_64.whl (14.6MB) ... Installing collected packages: pyparsing, cycler, python-dateutil, numpy, pytz, matplotlib Successfully installed cycler-0.10.0 matplotlib-2.0.2 numpy-1.13.0 pyparsing-2.2.0 python-dateutil-2.6.0 pytz-2017.2

当matplotlib和他的依赖包都安装好之后,你可以重新进入交互解释器:

  1. python
  1. import matplotlib

现在就不会有报错了,这个安装好的模块将可以在文件或命令行中自由使用。

退出Python交互控制台

退出Python交互控制台有两种方法:使用快捷键,或是一个Python函数。

在"类*nix"(Mac,Unix,Linux)系统中使用快捷键CTRL + D,或是在Windows系统中使用快捷键CTRL + Z,之后再次键入一次CTRL将终结Python控制台,并退出到你原来的命令行环境:

...
>>> age_at_death = death_year - birth_year
>>> print(age_at_death)
53
>>> 
sammy@ubuntu:~/environments$ 

另一种选择是使用Python的函数quit(),同样会结束Python控制台,退出到你原来的命令行环境:

>>> octopus = 'Ollie'
>>> quit()
sammy@PythonUbuntu:~/environments$ 

当你使用quit()后,它将会被记录在你的历史文件中。但键盘的快捷键CTRL + D则不会:

File: /home/sammy/.python_history
...
age_at_death = death_year - birth_year
print(age_at_death)
octopus = 'Ollie'
quit()

退出Python解释器的两种方式可自由选择,取决你觉得哪个对你的"工作流程和记录历史"的需求更合适。

获取历史

Python解释器提供的有用功能之一,是你可以看到你所有的命令历史。这些历史在"类*nix"系统中被存储在.python_history文件中,你可以用像nano这类的文本编辑器去查看:

  1. nano ~/.python_history

当你用文本编辑器打开它之后,你的Python历史文件看上去类似于下面的格式,并包含有你自己的命令历史:

File: /home/sammy/.python_history
import pygame
quit()
if 10 > 5:
    print("hello, world")
else:
    print("nope")
sammy = 'Sammy'
shark = 'Shark'
...

当你用好文件之后,你可以使用CTRL + X退出nano。

通过记录所有的Python历史,你将可以获得你之前试验过的所有指令。你可以复制、粘贴到这些代码到Python文件中,或是Jupyter Notebook中,去修改并使用这些之前的命令行代码。

总结

Python的交互控制台提供了一个可以试验Python代码的空间。你可以用它进行测试,设计出逻辑方法等等。

若想在Python文件里debug,你可以使用Python的code模块去用交互控制台打开一个文件。这里是更加具体的指南如何用交互控制台debug Python.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Default avatar
Gongxia Chen

translator


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel