Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
An Introduction To Python and Python on the Ras...
Search
Jamie Matthews
November 27, 2012
Programming
4
280
An Introduction To Python and Python on the Raspberry Pi
Slides from my talk at the BrightonPi / BrightonPy “Raspberry Pi Jam” night.
Jamie Matthews
November 27, 2012
Tweet
Share
More Decks by Jamie Matthews
See All by Jamie Matthews
MicroPython
j4mie
1
68
Other Decks in Programming
See All in Programming
Azure AI Foundryではじめてのマルチエージェントワークフロー
seosoft
0
150
今ならAmazon ECSのサービス間通信をどう選ぶか / Selection of ECS Interservice Communication 2025
tkikuc
20
3.8k
20250628_非エンジニアがバイブコーディングしてみた
ponponmikankan
0
530
Quand Symfony, ApiPlatform, OpenAI et LangChain s'allient pour exploiter vos PDF : de la théorie à la production…
ahmedbhs123
0
110
イベントストーミング図からコードへの変換手順 / Procedure for Converting Event Storming Diagrams to Code
nrslib
1
550
プロダクト志向ってなんなんだろうね
righttouch
PRO
0
170
Rubyでやりたい駆動開発 / Ruby driven development
chobishiba
1
520
datadog dash 2025 LLM observability for reliability and stability
ivry_presentationmaterials
0
350
ペアプロ × 生成AI 現場での実践と課題について / generative-ai-in-pair-programming
codmoninc
0
150
Go1.25からのGOMAXPROCS
kuro_kurorrr
1
830
なぜ適用するか、移行して理解するClean Architecture 〜構造を超えて設計を継承する〜 / Why Apply, Migrate and Understand Clean Architecture - Inherit Design Beyond Structure
seike460
PRO
1
710
PipeCDのプラグイン化で目指すところ
warashi
1
230
Featured
See All Featured
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
10
940
RailsConf 2023
tenderlove
30
1.1k
Producing Creativity
orderedlist
PRO
346
40k
Music & Morning Musume
bryan
46
6.6k
Building an army of robots
kneath
306
45k
GitHub's CSS Performance
jonrohan
1031
460k
Optimizing for Happiness
mojombo
379
70k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
138
34k
Bootstrapping a Software Product
garrettdimon
PRO
307
110k
Build your cross-platform service in a week with App Engine
jlugia
231
18k
A designer walks into a library…
pauljervisheath
207
24k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
181
53k
Transcript
An Introduction To Python and Python on the Raspberry Pi
Jamie Matthews Raspberry Pi Jam - “Py vs Pi” 27th November 2012
Agenda About me Why Python? A brief tour Python on
the Raspberry Pi Python for hardware hacking Discussion?
BrightonPy
None
None
Before we start.
http://flic.kr/p/8JzoGv
http://flic.kr/p/4kzYrd
None
Python
Not named after this http://flic.kr/p/9pb6Zj
Named after this
(but yes, the logo is a snake)
PyPI Python Package Index http://pypi.python.org
PyPy A fast, compliant alternative implementation of the Python language
http://pypy.org
Raspberry Pi
BrightonPy BrightonPi
Proposal: BrightonPie
Anyway.
A Brief History of Python Created by Guido van Rossum
Implementation started in 1989 Python 1.0 released January 1994 Python 2.0 released October 2000 Python 3.0 released December 2008 *
Why Python?
Why Python? Emphasis on readability Widely used Batteries included (or,
at least, available) Multi-paradigm
Readability “Programs must be written for people to read, and
only incidentally for machines to execute” -H. Abelson and G. Sussman (in "The Structure and Interpretation of Computer Programs)
“Nobody ever got fired for choosing Python” Scientific communities Web
communities Google, NASA, US government
Batteries included (or, at least, available)
Standard Library subprocess csv json sqlite3 os datetime logging smtplib
multiprocessing urllib2 posix signal pickle zlib hashlib
Python Package Index 25k+ third-party packages
Plays well with others Easy to write extensions in C
for speed Easy to communicate with other processes Jython, IronPython, PyPy Embeddable as a scripting language
Multi-paradigm
“Python is a scripting language”
Scripts “programs written for a software environment that automate the
execution of tasks which could alternatively be executed one-by-one by a human operator.” - wikipedia
Scripts “programs written for a software environment that automate the
execution of tasks which could alternatively be executed one-by-one by a human operator.” - wikipedia
Scripts Real programs
“Scripts” “Real programs”
Scripts Real programs
Scripts Real programs
Scripts Real programs
Imperative Object Oriented Functional
Let’s see some code (just a little)
Where to start 1. Open a terminal 2. Type python
None
None
Running code in a file 1. Create a file with
a .py extension 2. Put some code in it 3. At a terminal prompt, type python yourfile.py
Basic types Integers: 42 Floats: 3.141 Strings: "Hello, Brighton"
Basic types Lists: [1, 2, 4, 8, 16] Tuples: (1,
"Hello", 5.2) Dictionaries: {"greeting": "Hello", "location": "Brighton"}
Names x = 5 5 x Names are labels attached
to things
Names 5 x y Names are labels attached to things
x = 5 y = x
Control structures location = "Brighton" if location == "Brighton": print
"Hello, Brighton!" else: print "How unfortunate"
Control structures places = ["Sussex", "Cornwall"] for place in places:
print place
Functions def greet(location): if location == "Brighton": print "Hello, Brighton!"
else: print "How unfortunate" greet("Brighton")
Classes class MyClass(object): def say_hello(self): print "Hello!" my_instance = MyClass()
my_instance.say_hello()
Aside: significant whitespace
Brackety languages function greet(location) { if (location === "Brighton") {
console.log("Hello, Brighton"); } else { console.log("How unfortunate"); } }
Python uses whitespace def greet(location): if location == "Brighton": print
"Hello, Brighton!" else: print "How unfortunate"
Whitespace is significant def greet(location): !!!!if location == "Brighton": !!!!!!!!print
"Hello, Brighton!" !!!!else: !!!!!!!!print "How unfortunate"
Whitespace is significant def greet(location): !!!!if location == "Brighton": !!!!!!!!print
"Hello, Brighton!" !!!!else: !!!!!!!!!print "How unfortunate"
Whitespace is significant def greet(location): if location == "Brighton": print
"Hello, Brighton!" else: print "How unfortunate" (actually, this works fine)
Whitespace is significant def greet(location): !!!!if location == "Brighton": !!!!!!!!print
"Hello, Brighton!" !!!!else: !!!!print "How unfortunate" IndentationError: expected an indented block
Whitespace is boring 1. Use an editor that indents code
automatically 2. Set it to indent with four spaces 3. Get on with your life Aside over
Using code from elsewhere Every Python file is a namespace.
You can import names from other files. You can also create packages (namespaces) consisting of multiple files and import names from them.
def greet(location): if location == "Brighton": print "Hello, Brighton!" else:
print "How unfortunate" greeter.py
def greet(location): if location == "Brighton": print "Hello, Brighton!" else:
print "How unfortunate" from greeter import greet greeter.py anotherfile.py
def greet(location): if location == "Brighton": print "Hello, Brighton!" else:
print "How unfortunate" from greeter import greet greeter.py anotherfile.py
def greet(location): if location == "Brighton": print "Hello, Brighton!" else:
print "How unfortunate" from greeter import greet greet("Brighton") greeter.py anotherfile.py
A (tiny) real example
A (tiny) real example from urllib2 import urlopen >
A (tiny) real example from urllib2 import urlopen response =
urlopen('http://jsonip.com/') >
A (tiny) real example from urllib2 import urlopen response =
urlopen('http://jsonip.com/') print response.read() >
A (tiny) real example from urllib2 import urlopen response =
urlopen('http://jsonip.com/') print response.read() {"ip":"87.xxx.xxx.xxx","about":"/about"} >
A (tiny) real example from urllib2 import urlopen import json
response = urlopen('http://jsonip.com/') data = json.loads(response.read()) print data['ip'] >
A (tiny) real example from urllib2 import urlopen import json
response = urlopen('http://jsonip.com/') data = json.loads(response.read()) print data['ip'] >
A (tiny) real example from urllib2 import urlopen import json
response = urlopen('http://jsonip.com/') data = json.loads(response.read()) print data['ip'] >
A (tiny) real example from urllib2 import urlopen import json
response = urlopen('http://jsonip.com/') data = json.loads(response.read()) print data['ip'] 87.xxx.xxx.xxx >
Things you should know about virtualenv for dependency isolation pip
for package management sudo apt-get install python-virtualenv mkdir mynewproject && cd mynewproject virtualenv env source env/bin/activate pip install somepackage vim mypythonfile.py python mypythonfile.py (Google them)
Further reading python.org Learn Python The Hard Way Python Module
of the Week
Python on the Raspberry Pi
Raspberry Pi is a real computer Roughly equivalent to an
Amazon EC2 Micro Instance (512MB version) Raspbian comes with Python 2.7.3 and 3.2.3 Web sites, web crawlers, social media robots, notification hubs...
Some useful libraries
Requests HTTP for Humans import requests r = requests.get('http://jsonip.com') print
r.json['ip']
PyQuery jQuery in Python (good for scraping) from pyquery import
PyQuery as pq print pq('http://brightonpy.org').find('h1').text() # prints 'Brighton and Hove Python User Group'
Flask A tiny web framework from flask import Flask app
= Flask(__name__) @app.route("/") def hello(): return "Hello World!" app.run()
“Professor Cox wrote the control code in Python”
But you could do all this on your laptop (or
on EC2)
“What could I do with a Raspberry Pi?”
“What couldn’t I do without a Raspberry Pi?”
Raspberry Pi is interesting because...
It’s small It’s cheap It’s low power
GPIO General Purpose Input/Output
Raspberry Pi <=> GPIO <=> Real world Inputs, outputs Sensors
and blinky lights
GPIO in Python pip install rpi.gpio http://code.google.com/p/raspberry-gpio-python/ import RPi.GPIO as
gpio gpio.setup(18, gpio.OUT) gpio.output(18, False)
Be careful “These interfaces are not plug and play and
require care to avoid miswiring. The pins use a 3V3 logic level and are not tolerant of 5V levels” - RPi Wiki
Arduino Another tiny computer Much, much lower powered than Raspberry
Pi Much better for physical computing No internet connection, can’t run Python £10-30 (several models)
Raspberry Pi Arduino The Real World Serial (over USB)
Serial Port import serial SERIALPORT = "/dev/tty.usbserial-FTDK0P3M" ser = serial.Serial(SERIALPORT,
9600) ser.write('somedata')
Physical Gmail Notifier http://j4mie.org/blog/how-to-make-a-physical-gmail-notifier/ WARNING: Very old article (2008). Probably
crappy Python code. Required constant connection to laptop. Use RPi instead!
Another crazy idea
Another crazy idea Energy monitor without special hardware or Arduino
Raspberry Pi, cheap webcam, Python
None
None
None
None
(or just use OCR)
* because everybody loves The Cloud
Mmm, data
Summary Python is easy, fun and powerful. The Raspberry Pi
lets you run Python anywhere. Imagine the possibilities.TM
“What couldn’t I do without a Raspberry Pi?”
Thanks. BrightonPy @j4mie mtth.org dabapps.com brightonpy.org