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
負債になりにくいCSSをデザイナとつくるには?
fsubal
9
2.3k
[JAWS-UG横浜 #80] うわっ…今年のServerless アップデート、少なすぎ…?
maroon1st
1
170
Domain-Driven Transformation
hschwentner
2
1.9k
『GO』アプリ バックエンドサーバのコスト削減
mot_techtalk
0
130
AWS Lambda functions with C# 用の Dev Container Template を作ってみた件
mappie_kochi
0
240
Pythonでもちょっとリッチな見た目のアプリを設計してみる
ueponx
1
480
Kubernetes History Inspector(KHI)を触ってみた
bells17
0
200
社内フレームワークとその依存性解決 / in-house framework and its dependency management
vvakame
1
550
Kanzawa.rbのLT大会を支える技術の裏側を変更する Ruby on Rails + Litestream 編
muryoimpl
0
220
Open source software: how to live long and go far
gaelvaroquaux
0
620
【PHP】破壊的バージョンアップと戦った話〜決断と説得
satoshi256kbyte
0
120
第3回関東Kaggler会_AtCoderはKaggleの役に立つ
chettub
3
890
Featured
See All Featured
What’s in a name? Adding method to the madness
productmarketing
PRO
22
3.3k
The Art of Programming - Codeland 2020
erikaheidi
53
13k
Large-scale JavaScript Application Architecture
addyosmani
510
110k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
59k
How to Ace a Technical Interview
jacobian
276
23k
What's in a price? How to price your products and services
michaelherold
244
12k
Building Your Own Lightsaber
phodgson
104
6.2k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
27
1.9k
How GitHub (no longer) Works
holman
313
140k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
99
18k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
366
25k
Building a Scalable Design System with Sketch
lauravandoore
460
33k
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