Fri: Updated file
Download
Report
Transcript Fri: Updated file
Python III
N Amanquah
Python on Samsung etc
To use Python on a non-Nokia Symbian device,
obtain manufacturer signed SIS file of the Python
runtime.
Available at the respective manufacturer
developer websites. Eg a Samsung signed version
of Python runtime (1.4.5) is available at
http://bit.ly/bxc7Fl
Samsung GT-I7110 , GT-I8510
Source: http://wiki.forum.nokia.com/index.php/Python_on_Symbian/01._Introduction
(09-Feb-2011)
Location & Messaging
Location
import location
#Mobile Country Code, Mobile Network Code,
#Location Area Code, and Cell ID
(mcc, mnc, lac, cellid) = location.gsm_location()
SMS Messaging
import messaging
sms_send(recipient, message)
Forms
Form(fields[, flags=0 ])
fields are tuples (label, type[, value ])
label is a Unicode string
types: 'text', 'number', 'date', 'time', 'combo' or
'float'
value for combo: ([choice label ...], index)
# create a list to be used in 'combo' selection mode
model = [u'6600', u'6630', u'7610', u'N90', u'N70']
data = [(u'Mobile','text', u'Nokia'),(u'Model','combo',
(model,0)),(u'Amount','number', 5), (u'Date','date'),
(u'Time','time')]
# set the view/edit mode of the form
flags = appuifw.FFormEditModeOnly
# creates the form
f = appuifw.Form(data, flags)
# make the form visible on the UI
f.execute()
More on Forms:
Look at info_tabs_forms link on mobiLenin
# Example script: form.py
Also see example in
“Programming_with_PyS60_1_2”
-page 24 and appendix G ***very important
• See how databases can be built locally
Date & Time
http://effbot.org/librarybook/datetime.htm
The datetime type represents a date and a time
during that day.
The date type represents just a date, between
year 1 and 9999 (see below for more about the
calendar used by the datetime module)
The time type represents a time, independent of
the date.
The timedelta type represents the difference
between two time or date objects.
Mobile Apps Ideas
Mobile App Ideas - mashup
http://www.zdnet.com/blog/igeneration/how-students-used-tech-to-beat-protestpolice-kettling-tactics/8046?tag=nl.e539
How students used tech to beat protest police 'kettling' tactics
Fleeing riot police on foot? There’s an app for that.
Two graduate students, angry in response to the police tactics used on students
exhibiting their legitimate right to protest, have taken their fight to the mobile
platform: a new smartphone application to avoid police cordens amid planned
protests.
Sukey runs as a mobile web application designed for peaceful protesters to remain on
the march. By submitting text messages of where police officers are collecting,
trouble hotspots and areas which have been blocked off already, it allows a map to
be generated on the phone browser to assist legitimate protesters in avoiding
trouble.
It employs a range of crowdsourcing submissions, ranging from Twitter hashtags to
geotagging photos on Flickr. It is a real-time citizen powered solution to a citizen
brought problem.
Mobile App ideas
Utilities
• Stop watch, Count down timer
• Large clock /time display
• Scientific Calculator
Bible
Budget/expenditure tracker
Education: question and answer (objectives?)
Course registration
MFocus
Health – book appointment to see doc etc
Python- The language:
Objects
N Amanquah
Based on Guido Van Rossum’s Python tutorial
Functions, Procedures
def name(arg1, arg2, ...):
"""documentation""" # optional doc string,
statements
return
return expression
# from procedure
# from function
First line of comments, spacing of contents with 3
quotes preserved
** from Guido Van Rossum’s python tutorial
Example Function
def gcd(a, b):
"greatest common divisor"
while a != 0:
a, b = b%a, a # parallel assignment
return b
Print documentation:
>>> gcd.__doc__
'greatest common divisor'
>>> gcd(12, 20)
4
Classes
class name:
"documentation"
statements
-orclass name(base1, base2, ...):
...
Most, statements are method definitions:
def name(self, arg1, arg2, ...):
...
May also be class variable assignments
Example Class
class Stack:
"A well-known data structure…"
def __init__(self):
self.items = []
def push(self, x):
self.items.append(x)
def pop(self):
x = self.items[-1]
del self.items[-1]
return x
# constructor
# the sky is the limit
# what happens if it’s empty?
def empty(self):
return len(self.items) == 0
# Boolean result
Using Classes
To create an instance, simply call the class object:
x = Stack() # no 'new' operator!
To use methods of the instance, call using dot notation:
x.empty()
# -> 1
x.push(1)
# [1]
x.empty()
# -> 0
x.push("hello")
# [1, "hello"]
x.pop()
# -> "hello" # [1]
To inspect instance variables, use dot notation:
x.items
# -> [1]
Subclassing
class FancyStack(Stack):
"stack with added ability to inspect inferior stack items"
def peek(self, n):
"peek(0) returns top; peek(-1) returns item below that; etc."
size = len(self.items)
assert 0 <= n < size
# test precondition
return self.items[size-1-n]
#assert will throw error if false
Subclassing (2)
class LimitedStack(FancyStack):
"fancy stack with limit on stack size"
def __init__(self, limit):
self.limit = limit
FancyStack.__init__(self)
# base class constructor
def push(self, x):
assert len(self.items) < self.limit
FancyStack.push(self, x)
# "super" method call
Class / Instance Variables
class Connection:
verbose = 0
def __init__(self, host):
self.host = host
def debug(self, v):
self.verbose = v
def connect(self):
if self.verbose:
print "connecting to", self.host
# class variable
# instance variable
# make instance variable!
# class or instance variable?
Instance Variable Rules
On use via instance (self.x), search order:
• (1) instance, (2) class, (3) base classes
• this also works for method lookup
On assignment via instance (self.x = ...):
• always makes an instance variable
Class variables "default" for instance variables
But...!
• mutable class variable: one copy shared by all
• mutable instance variable: each instance its
own
Modules
Collection of stuff in foo.py file
• functions, classes, variables
Importing modules:
• import re; print re.match("[a-z]+", s)
• from re import match; print match("[a-z]+", s)
Import with rename:
• import re as regex
• from re import match as m
• Before Python 2.0:
import re; regex = re; del re
Packages
Collection of modules in directory
Must have __init__.py file
May contain subpackages
Import syntax:
• from P.Q.M import foo; print foo()
• from P.Q import M; print M.foo()
• import P.Q.M; print P.Q.M.foo()
• import P.Q.M as M; print M.foo()
# new
Catching Exceptions
def foo(x):
return 1/x
def bar(x):
try:
print foo(x)
except ZeroDivisionError, message:
print "Can’t divide by zero:", message
bar(0)
Other exceptions: ArithmeticError, EOFError ,
IOError etc see reference
Try-finally: Cleanup
f = open(file)
try:
process_file(f)
finally:
f.close()
# always executed
print "OK"
# always
Error handling
n=41
try:
print n
assert n>10 ,"our msg"
except AssertionError, vdetail:
print "bad value of n"
print vdetail
else:
print "else part"
finally:
print "finally part"
print "finished“
#else part executed if no exception, finally is always executed.
Catch more than one exception
try:
print n/0
assert n>10 ,"our msg"
except (AssertionError, ZeroDivisionError), msg:
print "bad value of n"
print msg
…
Division Zero msg will be printed. Note tuple of
possibilities
Raising Exceptions
raise IndexError
raise IndexError("k out of range")
raise IndexError, "k out of range"
try:
something
except: # catch everything
print "Oops"
raise # reraise
More on Exceptions
User-defined exceptions
• subclass Exception or any other standard exception
File Objects
f = open(filename[, mode[, buffersize])
• mode can be "r", "w", "a" (like C stdio); default "r"
• append "b" for binary mode
• append "+" for read/write open (for updating file)
w+ truncates file
• buffersize: 0=unbuffered; 1=line-buffered; buffered
methods:
• read([nbytes]), readline(), readlines()
• write(string), writelines(list)
• seek(pos[, how]), tell() # tell file’s current pos.
• flush(), close()
Standard Library
Core:
• os, sys, string,…
Regular expressions:
• re module; Perl-5 style patterns and matching
rules
Internet:
• socket, httplib, htmllib, ftplib, smtplib, ...
Keyboard Input
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
Utilities
N Amanquah
OS Reads and Writes
Get the Contents of a Directory
import e32
import os
# define the directory to read
imagedir=u'c:\\nokia\images'
# read the directory
files=map(unicode,os.listdir(imagedir))
**MAP:
Apply function to every item of iterable and return a list of the results.
Example script : os_dir_read.py
Reading
Read an image into a variable:
import e32
import os
# read the directory
f=open('c:\\nokia\\images\\testimg.jpg'','rb')
test = f.read()
f.close()
Writing Files
# define the directory and file name to write the file into
imagedir=u'c:\\writetest.txt'
epoc32\wins\c
import sysinfo
# create the file
file = open(imagedir,'w')
# write some text into it
file.write(str(sysinfo.battery())
# close the file
file.close()
Example script : os_dir_write.py
Reading and Writing OS
Settings
Write and read settings to/from the OS:
Write several variables with attached values as settings into
a file on the OS, and also read the them.
SYSINFO:
import sysinfo
sysinfo.battery() #batt level (0-7) or 0-100, 0 on emulator
sysinfo.imei() #00000000 on emulator
sysinfo.free_drivespace()
sysinfo.total_ram()
sysinfo.signal()
SEE PYTHON API!
Sound Recording and Playback
Program an application that can record and play a sound,
controlled from the application menu
import audio
audio.Sound.play() for playing the sound
audio.Sound.record() to record
2. You need to open and close sound files by using:
audio.Sound.open(filename)
audio.Sound.close()
Example: ex_soundrecorder_descr.py
Timers etc
X=Ao_Timer
X.after(interval, [callback])
X.cancel()
time module.
time.sleep(secs)
Appuifw.app methods
Appuifw.app.orientation
• #automatic, portrait, ‘landscape’
Appuifw.app.activate_tab(index)
• Activates the tab index counting from zero.
set tabs(tab texts[,callback=None ])
• Tab_texts is a list
Other objects
Text is a text editor UI control. (b) Listbox: single-line item or a
double-item listbox. Above is single item listbox with icons
More objects
Use a content handler to play /handle specific file
types eg web address in a browser, mp3 in media
player
i=appuifw.InfoPopup()
i.show(u"Here is the tip.", (0, 0), 5000, 0, appuifw.EHRightVCenter)
See API p 33/110
show(text, [(x coord, y coord), time shown, time before, alignment ])
The globalui module allows a global note and
query to be launched from an application which
does not have a UI environment
• global_note(note text[, type ])
More objects
Sensors
• acceleration sensor: raises events about the 3axes acceleration of the device
• tapping sensor: when the device was tapped
twice on the front side
• rotation sensor: raises an event based on the
orientation of the device.
• See API p54/110
Positioning see API p63/110
Others: data management : contacts, inbox, calendar
Deployment
Package with PyS60 Application Packager