python on pi

26
Python on Pi

Upload: swee-meng-ng

Post on 22-Jan-2018

569 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Python on pi

Python on Pi

Page 2: Python on pi

Who am I?

Page 3: Python on pi

What is python

Page 4: Python on pi

Created in the late 80’s

Page 5: Python on pi

General purpose language

Page 6: Python on pi

Supported many OS/Hardware

Page 7: Python on pi

It is supported by the pi foundation

Page 8: Python on pi

● http://learnpythonthehardway.org/

● https://docs.python.org/

Where to learn python

Page 9: Python on pi

few tip for good python

Page 10: Python on pi

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

Page 11: Python on pi

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

Page 12: Python on pi

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)$

Page 13: Python on pi

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()

Page 14: Python on pi

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

Page 15: Python on pi

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

Page 16: Python on pi

Use new style

● People begin to use python 3 in production

● A number of chances to syntax

print(“spam”)

instead of

print “spam”

Page 17: Python on pi

Best tools

Page 18: Python on pi

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()

Page 19: Python on pi

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

Page 20: Python on pi

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')

Page 21: Python on pi

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:])

Page 22: Python on pi

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)

Page 23: Python on pi

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.

Page 24: Python on pi

There’s more!

● But i’m can’t fit everything to slide

● so Ask me!

Page 25: Python on pi

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/

Page 26: Python on pi

Hope that’s helpful