在本章中,我们将开始用 Raspberry Pi 编写 python 程序。python 是 Raspberry Pi 的官方编程语言,名称中用 Pi 表示
本章将介绍以下主题:
Python 以两个版本预先安装在 Raspbian 上,版本 2.7.14 和 3.6.5(截至本文撰写之时)分别代表 Python 2 和 Python 3。这两个版本之间的差异超出了本书的范围。除非另有说明,否则我们将在本书中使用 Python 3。
在这个项目中,我们将熟悉 Raspberry Pi 上的 Python 开发。您可能习惯于在其他系统(如 Windows、macOS 和 Linux)上使用开发工具或集成开发环境(IDE)。在本章中,我们将使用树莓 Pi 作为开发机器。我们将慢慢地从 Python 开始,让我们的开发工作顺利进行。
完成本项目需要以下内容:
以下是我们可以使用 Raspbian 在 Raspberry Pi 上进行 Python 开发的预装工具。这份清单绝不是我们用于发展的唯一工具。
由于 Python 预装了 Raspbian,启动它的一个简单方法是使用终端。正如我们在下面的屏幕截图中看到的,只需在终端窗口中键入python
作为命令提示符,即可访问 Python 解释器:
我们可以通过运行最简单的程序进行测试:
print 'hello'
注意命令后面一行中的 Python 版本,2.7.13。Raspbian 中的python
命令与 Python 2 绑定。为了访问 Python 3,我们必须在终端窗口中键入python3
命令:
集成开发和学习环境(空闲)自版本 1.5.2 以来一直是 Python 的默认 IDE。它是使用 Tkinter GUI 工具包用 Python 编写的,目的是为初学者提供一个简单的 IDE:
IDLE 具有一个多窗口文本编辑器,具有自动完成、语法突出显示和智能缩进功能。任何使用过 Python 的人都应该熟悉 IDLE。Raspbian 中有两个 IDLE 版本,一个用于 Python 2,另一个用于 Python 3。两个程序都可以从应用程序菜单|编程中访问。
Thonny 是一个用 Raspbian 打包的 IDE。使用 Thonny,我们可以使用debug
函数计算表达式。Thonny 也可用于 macOS 和 Windows。
要加载 Thonny,请转到应用程序菜单|编程| Thonny:
以上是 Thonny 的默认屏幕。用于查看程序中变量的面板以及用于查看文件系统的面板都可以从“视图”菜单中打开和关闭。Thonny 结构紧凑,非常适合我们的项目。
在阅读本书的其余部分时,我们将进一步了解 Thonny。
让我们开始做一些编码。每当我开始使用一个新的操作系统进行开发时,我都喜欢复习一些基础知识,只是为了让我的注意力回到它上面(我特别要对我们这些非常熟悉凌晨编码的人说)。
访问 Python 的最简单方法是从终端访问。我们将运行一个简单的程序开始。从主工具栏加载终端,并在提示下键入python3
。键入以下行并点击输入:
from datetime import datetime
这一行将datetime
模块中的datetime
对象加载到我们的 Python 实例中。下一步键入以下内容并点击进入:
print(datetime.now())
您应该看到屏幕上打印的当前日期和时间:
让我们再举一个例子。在外壳中键入以下内容:
import pyjokes
这是一个用来讲编程笑话的图书馆。要打印笑话,请键入以下内容并点击输入:
pyjokes.get_joke()
您应该看到以下输出:
好吧,这可能不是你喜欢的(或者咖啡,对 Java 程序员来说)。然而,这个示例演示了导入 Python 模块并利用它是多么容易。
If you receive an ImportError
, it is because pyjokes
did not come pre-installed with your version of the OS. Similar to the following example, typing sudo pip3 install pyjokes
will install pyjokes
onto your Raspberry Pi.
这些 Python 模块的共同点是它们可供我们使用。我们只需将它们直接导入 shell 即可使用,因为它们是与我们的 Raspbian 操作系统一起预装的。但是,对于未安装的库呢?
让我们来举个例子。在 Python shell 中,键入以下内容并点击输入:
import weather
您应该看到以下内容:
由于我们的 Raspberry Pi 上没有安装weather
包,因此在尝试导入时会出现错误。为了安装该软件包,我们使用 Python 命令行实用程序pip
,或者在我们的例子中,对于 Python 3 使用pip3
:
pip3 install weather-api
weather-api
软件包。这个软件包将允许我们访问雅虎的天气信息!天气现在让我们尝试几个例子:
python3
并点击进入。现在,您应该回到 Python shell 中了from weather import Weather
from weather import Unit
weather
导入Weather
和Unit
。键入以下内容并点击输入: weather = Weather(unit=Unit.CELSIUS)
weather
的weather
对象。现在,让我们利用这个对象。键入以下内容并点击输入:lookup = weather.lookup(4118)
lookup
的变量,它是用代码4118
创建的,对应于加拿大多伦多市。键入以下内容并点击输入:condition = lookup.condition
condition
的变量,它通过lookup
变量包含加拿大多伦多市的当前天气信息。要查看此信息,请键入以下内容并点击输入:print(condition.text)
Partly Cloudy
现在我们已经看到,在 Raspberry Pi 上编写 Python 代码与在其他操作系统上编写 Python 代码一样简单,让我们进一步编写一个简单的程序。我们将使用 Thonny 进行此操作。
A Python module is a single Python file containing code that may be imported for use. A Python package is a collection of Python modules.
我们将编写一个包含类的简单 Python 程序。为了实现这一点,我们将使用 Thonny,这是一个与 Raspbian 一起预装的 Python IDE,具有出色的调试和变量内省功能。您会发现,它的易用性使其成为我们项目开发的理想选择。
我们将通过创建一个类来开始我们的程序。类可以看作是创建对象的模板。类包含方法和变量。要使用 Thonny 在 Python 中创建类,请执行以下操作:
class CurrentWeather:
weather_data={'Toronto':['13','partly sunny','8 km/h NW'],
'Montreal':['16','mostly sunny','22 km/h W'],
'Vancouver':['18','thunder showers','10 km/h NE'],
'New York':['17','mostly cloudy','5 km/h SE'],
'Los Angeles':['28','sunny','4 km/h SW'],
'London':['12','mostly cloudy','8 km/h NW'],
'Mumbai':['33','humid and foggy','2 km/h S']
}
def __init__(self, city):
self.city = city
def getTemperature(self):
return self.weather_data[self.city][0]
def getWeatherConditions(self):
return self.weather_data[self.city][1]
def getWindSpeed(self):
return self.weather_data[self.city][2]
如您所见,我们已经创建了一个名为CurrentWeather
的类,它将保存我们为哪个城市实例化该类的天气条件。我们正在使用一个类,因为它允许我们保持代码干净,并为以后使用外部类做好准备。
现在我们将从CurrentWeather
类创建一个对象。我们将使用London
作为我们的城市:
londonWeather = CurrentWeather('London')
我们刚刚在代码中从CurrentWeather
类创建了一个名为londonWeather
的对象。通过将'London'
传递给构造函数(init
,我们将新对象设置为只发送London
城市的天气信息。这是通过类属性 city(self.city
完成的。
weatherLondon.getTemperature()
你应该在下一行得到答案。
London
的天气状况,请键入以下内容:weatherLondon.getWeatherConditions()
你应该在下一行看到'mostly cloudy'
。
weatherLondon.getWindSpeed()
你应该上下一行。
我们的CurrentWeather
类模拟来自天气数据 web 服务的数据。我们类中的实际数据存储在weather_data
变量中。
In future code, whenever possible, we will wrap calls to web services in classes in order to keep things organized and make the code more readable.
让我们对代码做一点分析:
londonWeather
变量。我们可以看到londonWeather
是CurrentWeather
类型的对象。在 Object inspector 中,我们还可以看到属性 city 设置为'London'
。这种类型的变量检查在代码故障排除中非常有用。在编写代码时测试代码非常重要,这样您就可以及早发现错误:
CurrentWeather
类中: def getCity(self):
return self.city
CurrentWeather.py
的底部。第一行应具有与类定义相同的缩进,因为此函数不是类的一部分:if __name__ == "__main__":
currentWeather = CurrentWeather('Toronto')
wind_dir_str_len = 2
if currentWeather.getWindSpeed()[-2:-1] == ' ':
wind_dir_str_len = 1
print("The current temperature in",
currentWeather.getCity(),"is",
currentWeather.getTemperature(),
"degrees Celsius,",
"the weather conditions are",
currentWeather.getWeatherConditions(),
"and the wind is coming out of the",
currentWeather.getWindSpeed()[-(wind_dir_str_len):],
"direction with a speed of",
currentWeather.getWindSpeed()
[0:len(currentWeather.getWindSpeed())
-(wind_dir_str_len)]
)
The current temperature in Toronto is 13 degrees Celsius, the weather conditions are partly sunny and the wind is coming out of the NW direction with a speed of 8 km/h
The if __name__ == "__main__":
function allows us to test the class in the file directly as the if
statement will only be true if the file is run directly. In other words, imports of CurrentWeather.py
will not execute the code following the if
statement. We will explore this method more as we work our way through this book.
更通用的代码更灵活。下面是两个示例,说明如何使代码不那么具体。
wind_dir_str_len
变量用于确定风向线的长度。例如,S
的方向将只使用一个字符,而 NW 将使用两个字符。这样,当方向仅由一个字符表示时,输出中不包含额外的空间:
wind_dir_str_len = 2
if currentWeather.getWindSpeed()[-2:-1] == ' ':
wind_dir_str_len = 1
通过使用[-2:-1]
查找空格,我们可以确定此字符串的长度,如果有空格,则将其更改为1
(因为我们正在解析字符串末尾的两个字符)。
通过将getCity
方法添加到我们的类中,我们可以创建具有更通用名称的类,如currentWeather
而不是torontoWeather
。这使得重用代码变得很容易。我们可以通过更改以下行来证明这一点:
currentWeather = CurrentWeather('Toronto')
我们将其更改为:
currentWeather = CurrentWeather('Mumbai')
如果我们通过点击 run 按钮再次运行代码,我们会得到句子中所有条件的不同值:
The current temperature in Mumbai is 33 degrees Celsius, the weather conditions are humid and foggy and the wind is coming out of the S direction with a speed of 2 km/h
本章首先讨论了在 Raspbian 中可用于 Python 开发的各种工具。运行 Python 的最快、最简单的方法是从终端窗口。由于 Python 预先安装在 Raspbian 中,因此终端提示符中的python
命令将加载 Python(本例中为 Python 2)。为了让命令找到程序,不需要设置环境变量。Python 3 通过键入python3
从终端运行。
我们还简要介绍了 IDLE,它是 Python 开发的默认 IDE。IDLE 代表集成开发和学习环境,是初学者在学习 Python 时可以使用的优秀工具。
Thonny 是另一个与 Raspbian 一起预装的 Python IDE。Thonny 具有出色的调试和变量内省功能。它也是为 Python 初学者设计的,但是,它的易用性和对象检查器使它非常适合我们项目的开发。随着本书的阅读,我们将更多地使用 Thonny。
然后,我们直接开始编程,以使我们的开发工作顺利进行。我们从使用终端的简单表达式开始,以一个天气数据示例结束,该示例旨在模拟用于调用 web 服务的对象。
在第 3 章中使用 GPIO 连接外部世界中,我们将直接进入 Raspberry Pi 上最强大的编程功能——GPIO。GPIO 允许我们通过使用连接到 Raspberry Pi 上该端口的设备与现实世界进行交互。GPIO 编程将把我们的 Python 技能提升到一个全新的水平。
Thonny 可用于哪些操作系统?
如何从终端命令行输入 Python 2?
在 Thonny 中,我们使用哪个工具来查看对象内部的内容?
给出两个理由,说明为什么我们在天气示例代码中使用对象。
在CurrentWeather
类中添加一个名为getCity
的方法有什么好处?
你用什么语言写的?
打印当前日期和时间的两个步骤是什么?
在我们的代码中,我们如何补偿仅由一个字母表示的风速方向?
if __name__ =="__main__"
语句的作用是什么?
空闲代表什么?
Python3-面向对象编程作者:Dusty Phillips,Packt 出版社。*