python on pi
TRANSCRIPT
Python on Pi
Who am I?
What is python
Created in the late 80’s
General purpose language
Supported many OS/Hardware
It is supported by the pi foundation
● http://learnpythonthehardway.org/
● https://docs.python.org/
Where to learn python
few tip for good python
explore standard library
● python is battery included
● Have extensive library
○ unittest
○ json
○ csv
○ sqlite3
○ etc
● On the side is how you start a simple web
server to serve file on the directory the
command run
$ python -m SimpleHTTPServer 8000
$ echo '{"foo": "lorem", "bar": "ipsum"}' | python -
m json.tool
use ipython
● Advanced python shell
● feature
○ autocomplete
○ notebook capability, for sharing
○ syntax highlighting
● installation
○ sudo apt-get install ipython
○ pip install ipython
● There is also a notebook. but lets not go
there
$ ipython
Python 2.7.10 (default, Oct 14 2015, 16:09:02)
Type "copyright", "credits" or "license" for more information.
IPython 3.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import random
In [2]: print(random.randint())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-5c3017620459> in <module>()
----> 1 print(random.randint())
TypeError: randint() takes exactly 3 arguments (1 given)
In [3]: print(random.randint(1,10))
9
Use virtualenv(when possible)
● environment isolation
● Why?
○ python is used extensively as a tool on
linux
○ thus library might conflict
● Why not?
○ sometime it will compile c module
○ The pi OS might not have the necessary
header
● but there --system-site-package for a
reason
$ virtualenv --system-site-package pijam2015
New python executable in pijam2015/bin/python
Installing setuptools, pip, wheel...done.
$ source pijam2015/bin/activate
(pijam2015)$
Create a main function
● STOP writing code outside a function and
if __name__ == “__main__”
● Why?
○ Make testing easy
○ sometime you don’t want code to run when
you import a module
import random
def main():
print(random.randint(1,10))
if __name__ == “__main__”:
main()
use a *.local hostname
● Not exactly a python thing
● it is a domain for zeroconf networking
● avahi is installed on your pi anyway
● Just make sure the domain name is
unique
$ sudo echo “your_awesome_name.local” >
/etc/hostname
use pip
● Don’t download zip file
● standard python tools
● When you have internet connection use
pip
● When binary is available pip (wheel). It will
download it
$ sudo pip install something
$ sudo pip remove something
Use new style
● People begin to use python 3 in production
● A number of chances to syntax
print(“spam”)
instead of
print “spam”
Best tools
use request
● http library
● easy to use
● not on standard lib
● install
○ pip install requests
○ sudo apt-get install python-requests
import requests
def main():
r = requests.get(“google.com”)
print(r.status_code)
if __name__ == “__main__”:
main()
Panda the data cruncher
● make data processing easy
● introduce data frame
● can import/export to csv
● Install
○ sudo apt-get install python-pandas
● Use system package version. It is faster
get the source code at
https://github.com/sweemeng/klpijam2015_dem
o/blob/master/sense_plotter.py
Matplotlib
● standard plotting library
● save image locally
● if headless set matplotlib.use('Agg')
● can be complicated. but powerful
● install
○ pip install python-matplotlib
○ sudo apt-get install python-matplotlib
● fyi if you installed pandas matplotlib is
installed as a dependency
n [1]: import matplotlib
In [2]: matplotlib.use('Agg')
In [3]: import matplotlib.pyplot as plt
In [4]: fig = plt.figure()
In [5]: plt.plot([1,2,3,4])
Out[5]: [<matplotlib.lines.Line2D at 0x73fe9fd0>]
In [6]: fig.savefig('tmp.png')
Scikit-learn
● Add machine learning to code
● have many algorithm
● use system package version
● install
○ sudo apt-get install python-scikitlearn
from sklearn import svm
from sklearn import datasets
digits = datasets.load_digits()
clf = svm.SVC(gamma=0.001, C=100.)
clf.fit(digits.data[:-1], digits.target[:-1])
clf.predict(digits.data[-1:])
Web development
● plenty of choice.
● For powerful feature full framework, I like
django
● For no frill, no dependency, i like bottle
● For if I need serious flexibility I use flask.
from bottle import static_file, route, run, view, template
import os
@route("/static/<filename>")
def serve_file(filename):
return static_file(filename, root="./")
@route("/")
def directory():
content = os.listdir("./")
directory = []
for item in content:
if ".jpg" in item:
directory.append(item)
template_str = """
%for item in directory:
<img src="/static/{{item}}/><br/>
%end
"""
return template(template_str, directory=directory)
if __name__ == "__main__":
run(host="0.0.0.0", port="8080", debug=True)
Final tips
● sometime you might want to use system package, because it is precompiled
● system package is older
● lack new feature
● usually good enough
● standard library is extensive, explore it.
There’s more!
● But i’m can’t fit everything to slide
● so Ask me!
Source code
● A lot of this rely on the sense_hat that I got for hacking.
● But the code is https://github.com/sweemeng/klpijam2015_demo/
Hope that’s helpful