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
64
Other Decks in Programming
See All in Programming
TypeScript Graph でコードレビューの心理的障壁を乗り越える
ysk8hori
2
1.1k
NSOutlineView何もわからん:( 前編 / I Don't Understand About NSOutlineView :( Pt. 1
usagimaru
0
340
Why Jakarta EE Matters to Spring - and Vice Versa
ivargrimstad
0
1.1k
Amazon Bedrock Agentsを用いてアプリ開発してみた!
har1101
0
340
OnlineTestConf: Test Automation Friend or Foe
maaretp
0
110
Jakarta EE meets AI
ivargrimstad
0
210
Less waste, more joy, and a lot more green: How Quarkus makes Java better
hollycummins
0
100
EMになってからチームの成果を最大化するために取り組んだこと/ Maximize team performance as EM
nashiusagi
0
100
どうして僕の作ったクラスが手続き型と言われなきゃいけないんですか
akikogoto
1
120
とにかくAWS GameDay!AWSは世界の共通言語! / Anyway, AWS GameDay! AWS is the world's lingua franca!
seike460
PRO
1
890
Laravel や Symfony で手っ取り早く OpenAPI のドキュメントを作成する
azuki
2
120
リアーキテクチャxDDD 1年間の取り組みと進化
hsawaji
1
220
Featured
See All Featured
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
25
1.8k
Measuring & Analyzing Core Web Vitals
bluesmoon
4
130
How To Stay Up To Date on Web Technology
chriscoyier
788
250k
Facilitating Awesome Meetings
lara
50
6.1k
RailsConf 2023
tenderlove
29
900
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
8
900
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
126
18k
Designing for humans not robots
tammielis
250
25k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
159
15k
VelocityConf: Rendering Performance Case Studies
addyosmani
325
24k
Six Lessons from altMBA
skipperchong
27
3.5k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
250
21k
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