Python Tools for Raspberry Pi: Unleash the power of Python

Learn the Python Tools for Raspberry Pi and how to write a simple Python program in this article by Colin Dow, the owner and chief engineer of Sigma Rockets and Aerospace Inc.

The following are preinstalled tools that can be used for Python development on Raspberry Pi using Raspbian. This list is by no means the only tools used for development.

Python Tools for Raspberry Pi List

The Terminal

The first thing in the list of Python Tools for Raspberry Pi is the Terminal. As Python comes pre-installed with Raspbian, an easy way to launch it is to use the Terminal. As we can see in the following screenshot, the Python interpreter can be accessed by simply typing python as the command prompt in a Terminal window:

raspberry python tools terminal

We may test it out by running the simplest of programs:

print 'hello'Code language: Python (python)

Notice the Python version in the line after the command, 2.7.13. The python command in Raspbian is tied to Python 2. In order to access Python 3, we must type the python3 command in a Terminal window:

raspberry pi python3

Integrated Development and Learning Environment

The Integrated Development and Learning Environment (IDLE) has been the default IDE for Python since version 1.5.2. It is written in Python itself using the Tkinter GUI toolkit and is intended to be a simple IDE for beginners:

raspberry pi3 using python

IDLE features a multi-window text editor with auto-completion, syntax highlighting, and smart indent. IDLE should be familiar to anyone that has used Python. There are two versions of IDLE in Raspbian, one for Python 2 and the other for Python 3. Both programs are accessed from Application Menu | Programming.

Thonny

Thonny is an IDE that comes packaged with Raspbian. With Thonny, we may evaluate expressions by using the debug function. Thonny is also available for macOS and Windows.

To load Thonny, go to Application Menu | Programming | Thonny:

raspberry pi3 thony

Above is the default screen for Thonny. Panels to view variables in your program, as well as a panel to view the filesystem, are toggled on and off from the View menu. Thonny’s compact structure makes it ideal for our projects.

Using the Python command line in Raspberry Pi

Let’s start doing some coding using Python Tools for Raspberry Pi described above. Whenever I start using a new operating system for development, I like to go through some basics just to get my mind back into it (I’m speaking particularly to those of us who are all too familiar with coding into the wee hours of the morning).

The simplest way to access Python is from the Terminal. We will run a simple program to get started. Load the Terminal from the main toolbar and type python3 at the prompt. Type the following line and hit Enter:

from datetime import datetimeCode language: Python (python)

This line loads the datetime object from the datetime module into our instance of Python. Next, type the following and hit Enter:

print(datetime.now())Code language: Python (python)

You should see the current date and time printed to the screen.

Let’s try another example. Type the following into the shell:

import pyjokesCode language: JavaScript (javascript)

This is a library that’s used to tell programming jokes. To have a joke printed out, type the following and hit Enter:

pyjokes.get_joke()Code language: CSS (css)

Check the output so see if it works!

OK, so this may not be your cup of tea (or coffee, for the Java programmers out there). However, this example demonstrates how easy it is to import a Python module and utilize it.

Note: 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.

What these Python modules have in common is their availability for our use. We simply need to import them directly into the shell in order to use them, as they are pre-installed with our Raspbian operating system. However, what about libraries that are not installed?

Let’s try an example. In the Python shell, type the following and hit Enter:

import weatherCode language: JavaScript (javascript)

You should see the following:

Python tools for Raspberry Pi3

Since the weather package is not installed on our Raspberry Pi we get an error when trying to import. In order to install the package, we use the Python command-line utility pip, or in our case, pip3 for Python 3:

  1. Open up a new Terminal (make sure that you’re in a Terminal session and not a Python shell). Type the following:[shell]pip3 install weather-api[/shell]
    1. Hit Enter. You will see the following:Raspberry Pi weather with Python tool
    2. After the process is finished, we will have the weather-api package installed on our Raspberry Pi. This package will allow us to access weather information from Yahoo! Weather.

Now let’s try out a few examples:

    1. Type python3 and hit Enter. You should now be back in the Python shell.
    2. Type the following and hit Enter:
from weather import Weather
from weather import UnitCode language: JavaScript (javascript)

What we have done is imported Weather and Unit from weather. Type the following and hit Enter

weather = Weather(unit=Unit.CELSIUS)Code language: Python (python)
  • This instantiates a weather object called weather. Now, let’s make use of this object. Type the following and hit Enter:
lookup = weather.lookup(4118)
  • We now have a variable named lookup that’s been created with the code 4118, that corresponds to the city Toronto, Canada. Type the following and hit Enter:
condition = lookup.condition
  • We now have a variable called condition that contains the current weather information for the city of Toronto, Canada via the lookup variable. To view this information, type the following and hit Enter:
print(condition.text)Code language: CSS (css)
  • You should get a description of the weather conditions in Toronto, Canada. When I ran it, the following was returned:Partly Cloudy

Now that we’ve seen that writing Python code on the Raspberry Pi is just as easy as writing it on other operating systems, let’s take it a step further and write a simple program. We will use Thonny for this.

Note: 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.

Writing a simple Python program using Thonny

We will write a simple Python program that contains a class. To facilitate this, we will use Thonny, a Python IDE that comes pre-installed with Raspbian and has excellent debug and variable introspection functionalities. You will find that its ease of use makes it ideal for the development of our projects.

Creating the class

We will begin our program by creating a class. A class may be seen as a template for creating objects. A class contains methods and variables. To create a class in Python with Thonny, do the following:

Load Thonny through Application Menu | Programming | Thonny. Select New from the top left and type the following code:

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]Code language: Python (python)

As you can see, we’ve created a class called CurrentWeather that will hold weather conditions for whichever city we instantiated the class for. We are using a class as it will allow us to keep our code clean and prepare us for using outside classes later on.

Creating the object

We will now create an object from our CurrentWeather class. We will use London as our city:

    1. Click on the Run Current Script button (a green circle with a white arrow) in the top menu to load our code into the Python interpreter.
    2. At the command line of the Thonny shell, type the following and hit Enter:[python]londonWeather = CurrentWeather(‘London’)[/python]

More useful resources:

Raspberry Pi IoT: Sensors, InfluxDB, MQTT and Grafana

How to Deploy OpenCV on Raspberry Pi enabling machine vision

How to Build a Surveillance System with Raspberry Pi 3 and camera

We have just created an object in our code called londonWeather from our CurrentWeather class. By passing ‘London’ to the constructor (init), we set our new object to only send weather information for the city of London. This is done through the class attribute city (self.city).

Type the following at the shell command line:

weatherLondon.getTemperature()Code language: CSS (css)

You should get the answer ’12’ on the next line.

To view the weather conditions for London, type the following:

weatherLondon.getWeatherConditions()Code language: CSS (css)

You should see ‘mostly cloudy’ on the next line.

To get the wind speed, type the following and hit Enter:

weatherLondon.getWindSpeed()Code language: CSS (css)

You should get 8 km/h NW on the next line.

Our CurrentWeather class simulates data coming from a web service for weather data. The actual data in our class is stored in the weather_data variable.

Note: 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.

Using the object inspector

Let’s do a little analysis of our code:

  1. From the View menu, select Object inspector and Variables.
  2. Highlight the londonWeather variable under the Variables tab. We can see that  londonWeather is an object of type  CurrentWeather. In the Object inspector, we can also see that the attribute city is set to ‘London’. This type of variable inspection is invaluable in troubleshooting code.

Testing your class

It is very important to test your code as you write it so that you can catch errors early on:

  1. Add the following function to the CurrentWeather class:
def getCity(self):
return self.cityCode language: PHP (php)
  • Add the following to the bottom of CurrentWeather.py. The first line should have the same indentation as the class definition as this function is not part of the class:
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)]
)Code language: PHP (php)
  • Run the code by clicking on the Run current script button.

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

Note: 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.

Making the code flexible

Code that is more generic is more flexible. The following are two examples of how we can make the code less specific.

Example one

The wind_dir_str_len variable is used to determine the length of the string for wind direction. For example, a direction of S would only use one character, whereas NW would use two. This is done so that an extra space is not included in our output when the direction is represented by only one character:

wind_dir_str_len = 2
if currentWeather.getWindSpeed()[-2:-1] == ' ':
wind_dir_str_len = 1Code language: JavaScript (javascript)

By looking for a space using [-2:-1], we can determine the length of this string and change it to 1 if there is a space (as we are parsing back two characters from the end of the string).

Example two

By adding the getCity method to our class, we are able to create classes with more generic names like currentWeather as opposed to torontoWeather. This makes it easy to reuse our code. We can demonstrate this by changing the following line:

currentWeather = CurrentWeather('Toronto')Code language: JavaScript (javascript)

We will change it to this:

currentWeather = CurrentWeather('Mumbai')Code language: JavaScript (javascript)

If we run the code again by clicking on the Run button, we get different values for all the conditions in the sentence:

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

If you found this article helpful, you can explore Internet of Things Programming Projects to learn how to develop modern IoT solutions using Raspberry Pi 3 and Python. Internet of Things Programming Projects is for Python developers and programmers who are interested in building their own IoT applications and IoT-based projects.

  • Add Your Comment