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 Raspberry Pi
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
60
Other Decks in Programming
See All in Programming
C# 大統一理論推進委員会 会員のための Unity Package Manager プロジェクト構成案
monry
PRO
0
580
受託開発でGitLab CI を活用していく
xiombatsg
1
130
9年開発を牽引して見えてきた、共通化すべきものと個別でつくるもの ~プログラム言語~
shinout
1
310
Honoとhtmx
yusukebe
6
1.2k
Migrating to Signals: A Practical Workshop
manfredsteyer
PRO
0
290
DocC Tutorial と TCA におけるテスト機能の紹介
kalupas226
1
330
Enhancing Applications with Accessibility API
kishikawakatsumi
3
1.1k
自動テスト実行結果の目的を整理する / Organizing objectives of automated test results
twada
PRO
10
2.1k
Material 3で Material 2ぽい見た目にする
numeroanddev
2
250
CircleCIを活用して AWSへの継続的デリバリーを 実践する
coconala_engineer
1
110
自作ソフト(VMagicMirror)がVRMA対応してる話+実装のTips
bakudreameater
0
110
WinUI 3デモ - "CommunityToolkit.Mvvm"NuGetパッケージ編
andrewkeepcoding
0
140
Featured
See All Featured
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
8
8.2k
Designing for humans not robots
tammielis
247
25k
GraphQLの誤解/rethinking-graphql
sonatard
48
9.1k
ParisWeb 2013: Learning to Love: Crash Course in Emotional UX Design
dotmariusz
101
6.6k
Why Our Code Smells
bkeepers
PRO
330
56k
Infographics Made Easy
chrislema
237
18k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
501
140k
Writing Fast Ruby
sferik
619
59k
Designing the Hi-DPI Web
ddemaree
275
33k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
5
1.4k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
24
2.2k
The Invisible Customer
myddelton
114
12k
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