analitics

Pages

Wednesday, February 23, 2011

Just a simple python weather script.

Sometimes we need simple solutions. An example is displaying data on a computer screen using conky. under Linux.
Another example is the display of data without using the browser.
Whether you use Windows or Linux python scripts come to help. Here's a simple example written in python that can display weather data.

import urllib
from xml.dom import minidom

wurl = 'http://xml.weather.yahoo.com/forecastrss?p=%s'
wser = 'http://xml.weather.yahoo.com/ns/rss/1.0'

def weather_for_zip(zip_code):
    url = wurl % zip_code +'&u=c'
    dom = minidom.parse(urllib.urlopen(url))
    forecasts = []
    for node in dom.getElementsByTagNameNS(wser, 'forecast'):
        forecasts.append({
            'date': node.getAttribute('date'),
            'low': node.getAttribute('low'),
            'high': node.getAttribute('high'),
            'condition': node.getAttribute('text')
        })
    ycondition = dom.getElementsByTagNameNS(wser, 'condition')[0]
    return {
        'current_condition': ycondition.getAttribute('text'),
        'current_temp': ycondition.getAttribute('temp'),
        'forecasts': forecasts ,
        'title': dom.getElementsByTagName('title')[0].firstChild.data
    }
def main():
    a=weather_for_zip("ROXX0003")
    print '=================================='
    print '|',a['title'],'|'
    print '=================================='
    print '|current condition=',a['current_condition']
    print '|current temp     =',a['current_temp']
    print '=================================='
    print '|  today     =',a['forecasts'][0]['date']
    print '|  hight     =',a['forecasts'][0]['high']
    print '|  low       =',a['forecasts'][0]['low']
    print '|  condition =',a['forecasts'][0]['condition']
    print '=================================='
    print '|  tomorrow  =',a['forecasts'][1]['date']
    print '|  hight     =',a['forecasts'][1]['high']
    print '|  low       =',a['forecasts'][1]['low']
    print '|  condition =',a['forecasts'][1]['condition']
    print '=================================='

main()
Here is the result of script execution:

>>> 
==================================
| Yahoo! Weather - Bucharest, RO |
==================================
|current condition= Light Snow
|current temp     = -3
==================================
|  today     = 23 Feb 2011
|  hight     = 0
|  low       = -5
|  condition = Light Snow
==================================
|  tomorrow  = 24 Feb 2011
|  hight     = 0
|  low       = -4
|  condition = Mostly Cloudy
==================================
>>> 

Thursday, February 3, 2011

Read feed from sites.

Is a simple example for reading some feed.
I use two functions , first read url and secondary extract data.
This is the code source:

from xml.dom import minidom as dom
import urllib

def fetchPage(url):
    a = urllib.urlopen(url)
    return ''.join(a.readlines())


def extract(page):
    a = dom.parseString(page)
    item2 = a.getElementsByTagName('SendingDate')[0].firstChild.wholeText
    print "DATA ",item2
    item = a.getElementsByTagName('Cube')
    for i in item:
        if i.hasChildNodes() == True:
            e = i.getElementsByTagName('Rate')[10].firstChild.wholeText
            d = i.getElementsByTagName('Rate')[26].firstChild.wholeText
            print "EURO  ",e
            print "DOLAR ",d

if __name__=='__main__':
    page = fetchPage("http://www.bnro.ro/nbrfxrates.xml")

    extract(page)
Result is :

DATA  2011-02-03
EURO   4.2609
DOLAR  3.0921
This is all...

Python - calendar

Two simple example about calendar python module.
Show calendar 04 - 2011 :

>>> import calendar
>>> tc = calendar.TextCalendar(calendar.SUNDAY)
>>> print tc.formatmonth(2011,04)
     April 2011
Su Mo Tu We Th Fr Sa
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

>>>
Show calendar in HTML format :
>>> import calendar
>>> hc = calendar.HTMLCalendar(calendar.SUNDAY)
>>> print hc.formatmonth(2011,04)
;
The result is a HTML table with the calendar.
This is all .

Tuesday, August 3, 2010

Random module - another example

Random module is a module used in everyday programming.
Even if it is not used in the final software, he helps us to test various types of random data.
We present you a simple example - play with cards.
We chose a list of cards of one color for not having a large number of elements.
We exemplify the use of random module by analogy with a game of cards.
That it means: shuffle cards , select just one from cards and a choice selection of a defined number of cards.
Below you see the code used as an example.

>>> import random
>>> choice=random.choice
>>> shuffle=random.shuffle
>>> for i in range (9):
...     print choice(cards)
... 
Q
K
10
Q
2
2
10
K
6
>>> shuffle(cards)
>>> cards
[4, 7, 10, 'J', 3, 'Q', 6, 2, 'K', 9, 'A', 8, 5]
>>> sample=random.sample
>>> sample(cards,5)
[8, 'J', 2, 'Q', 10]
>>> sample(cards,5)
['A', 9, 4, 'K', 'Q']
>>> 
The random module docs

Saturday, July 3, 2010

The module matplotlib-0.99.3

The module matplotlib is a python 2D plotting library with a variety of hardcopy formats and interactive environments across platforms.
With just a few lines of code we can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc...
See images bellow or visit the gallery.

This module is version 0.99.3 for Python 2.5 and 2.6. We have modules for installation on operating systems like MacOS, Windows and Linux.
To use this module you must have install numpy module.
Now download module from here.
$python setup.py build
Use super user:
#python setup.py install
Try to load module:
$python
Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) 
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> 
It's working fine.

Sunday, June 27, 2010

Add text on image with PIL module.

It's easy to create images with PIL module.
This is the script:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf",25)
img=Image.new("RGBA", (200,200),(120,20,20))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(255,255,0),font=font)
draw = ImageDraw.Draw(img)
draw = ImageDraw.Draw(img)
img.save("a_test.png")
The only error that can occur is not to find the font.
In this case you must change the code line:
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf",25)
Here is the result script:

Wednesday, June 2, 2010

The HTMLParser module - just simple example

Basically this module is for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
On HTMLParse docs.
You will see the same example but with no explanation. The example is :

import HTMLParser
from HTMLParser import *
import urllib2 
from urllib2 import urlopen

class webancors(HTMLParser):
 def __init__(self, url):
  HTMLParser.__init__(self)
  r = urlopen(url)
  self.feed(r.read())

 def handle_starttag(self, tag, attrs):
  if tag == 'a' and attrs:
   print "Link: %s" % attrs[0][1]
I named the python file : spiderweb.py
I use python to import this file:

>>> import spiderweb
>>> spiderweb.webancors('http://www.yahoo.com')
Link: y-mast-sprite y-mast-txt web
Link: y-mast-link images
Link: y-mast-link video
Link: y-mast-link local
Link: y-mast-link shopping
Link: y-mast-link more
Link: p_13838465-sa-drawer
Link: y-hdr-link

>>> 
The method handle_starttag takes two arguments from HTMLParser.
This arguments, tag and attrs is used to return values.
Note :
The HTMLParser module has been renamed to html.parser in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
Use "http://" not just "www". If don't use "http://" you see errors.
Seam urllib2 have some troubles with:

  File "/usr/lib/python2.5/urllib2.py", line 241, in get_type
    raise ValueError, "unknown url type: %s" % self.__original

You can use all functions HTTParser class.

Saturday, May 22, 2010

The beauty of Python: subprocess module - part 3

This is just a simple example about module subprocess.
We need to install "espeak" . On fedora usse this command:
#yum install espeak

Now the example is:

>>> import subprocess   
>>> subprocess.call(["espeak", "-s 120","-p 100","This is a test"])
0
>>>   

This will speak "This is a test".
This is all .

The beauty of Python: Some examples with os and sys modules - part 2

Today i will tell about sys and os modules.
The module os has OS routines for Mac, NT, or Posix depending on what system we're on.
The module sys provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter.

Some useful functions with sys module.
>>> print sys.version
2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2]
>>> print sys.version_info
(2, 5, 2, 'final', 0)
>>> print sys.subversion
('CPython', 'tags/r252', '60911')
>>> print sys.platform 
linux2
>>> print sys.ps1
>>> 
>>> print sys.ps2
... 
>>> print sys.prefix
/usr
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk',
'/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages',
 '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric',
'/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10',
 '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', 
'/var/lib/python-support/python2.5/gtk-2.0']
>>> print sys.modules.keys()
['apt.os', 'email.iterators', 'apport.sys', 'random', 'apport.atexit', 'subprocess',
 'email.MIMEImage', 'gc', 'apport.pwd', 'os.path', 'encodings.encodings', 'email.mime',
 'email.MIMEText', 'xml', 'email.time', 'struct', 'tempfile', 'base64', 'apt.cache',
 'pyexpat.errors', 'apt_pkg', 'apport', 'email.binascii', 'email.Parser', 'zipimport',
 'apport.xml', 'xml.dom.copy', 'encodings.utf_8', 'apt.apt_pkg', 'email.quoprimime',
 'email.mime.text', 'email.urllib', 'email.FeedParser', 'signal', 'email.encoders',
 'pyexpat.model', 'apport.packaging_impl', 'apport.cStringIO', 'quopri',
 'email.Message', 'cStringIO', 'zlib', 'locale', 'email.charset', 'apport.fileutils',
 'xml.parsers.expat', 'atexit', 'email.quopriMIME', 'encodings', 'email.Generator',
 'apport.warnings', 'apport.problem_report', 'apt.fcntl', 'email.MIMEAudio', 'urllib',
 're', 'apt.select', 'email.quopri', 'apport.report', 'email.mime.base', 'email.errors',
 'email', 'math', 'fcntl', 'apport.os', 'apt.progress', 'UserDict', 'exceptions',
 'apport.grp', 'apport.shutil', 'codecs', 'xml.dom.domreg', 'email.Header', '_locale',
 'email.Iterators', 'socket', 'thread', 'traceback', 'apt.apt', 'e,
 'SUDO_COMMAND': '/bin/su', 'SUDO_GID': '999', 'SDL_VIDEO_CENTERED': '1',
 'PWD': '/home/mint/Desktop', 'COLORTERM': 'gnome-terminal', 'MAIL': '/var/mail/root'}
mail.Charset', 'xml.dom.xmlbuilder', 'os', 'marshal', 'apport.stat', 'apport.re',
 'apt.gettext', 'email.uu', '_sre', 'unittest', '__builtin__', 'apport.apport',
 'xml.parsers', 'apport.fnmatch', 'apport.urllib', 'operator', 'xml.parsers.pyexpat',
 'email.Errors', 'select', 'apt.string', 'apport.glob', 'apt.warnings', 'email.socket',
 'posixpath', 'email.base64MIME', 'errno', '_socket', 'binascii', 'email.Utils',
 'sre_constants', 'email.MIMEMessage', 'email._parseaddr', 'email.sys',
 'apport.traceback', 'apt.package', 'apt.random', 'xml.dom.NodeFilter',
 'email.MIMENonMultipart', '_codecs', 'apport.unittest', 'apport.apt', 'email.os',
 'email.utils', 'pwd', 'apport.time', 'copy', '_struct', '_types', 'email.email',
 'apt.cdrom', 'uu', 'xml.dom.minidom', 'apport_python_hook', 'apt', 'email.random',
 'posix', 'encodings.aliases', 'apt.sys', 'fnmatch', 'sre_parse', 'pickle', 'copy_reg',
 'sre_compile', '_random', 'site', 'email.base64', 'apt.errno', '__main__', 'problem_report',
 'pyexpat', 'email.MIMEBase', 'email.message', 'string', 'email.mime.nonmultipart',
 'apport.subprocess', 'shutil', 'strop', 'grp', 'encodings.codecs', 'gettext',
 'email.warnings', 'xml.dom.minicompat', 'email.MIMEMultipart', 'types', 'apport.tempfile',
 'stat', '_ssl', 'warnings', 'encodings.types', 'glob', 'email.re', 'sys', 'email.Encoders',
 'readline', 'email.cStringIO', 'xml.dom', 'xml.dom.xml', 'apport.signal', 'sitecustomize',
 'email.mime.email', 'email.base64mime', 'email.mime.multipart', 'apport.packaging',
 'urlparse', 'linecache', 'email.string', 'apt.re', 'time', 'gzip']


And now, some useful functions with os module.
>>> print os.uname()
('Linux', 'mint', '2.6.27-7-generic', '#1 SMP Fri Oct 24 06:42:44 UTC 2008', 'i686')
>>> print os.ttyname(1)
/dev/pts/0
>>> print os.times()
(0.050000000000000003, 0.02, 0.0, 0.0, 17186002.649999999)
>>> print os.environ
{'USERNAME': 'root', 'LANG': 'en_US.UTF-8', 'TERM': 'xterm', 'SHELL': '/bin/bash',
 'XDG_SESSION_COOKIE': '842d38513df1a6bb7490c8a14bf69489-1274456064.963733-1686354756',
 'SUDO_COMMAND': '/bin/su', 'SHLVL': '1', 'RUNNING_UNDER_GDM': 'yes', 'SUDO_UID': '999',
 'SUDO_GID': '999', 'PWD': '/home/mint/Desktop', 'LOGNAME': 'root', 'USER': 'root',
 'COLORTERM': 'gnome-terminal',
 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games',
 'MAIL': '/var/mail/root', 'SUDO_USER': 'mint', 'HOME': '/root', 'DISPLAY': ':0.0',
 '_': '/usr/bin/python', 'XAUTHORITY': '/home/mint/.Xauthority'}
>>> print os.mkdir('aaa')
None
>>> print os.mkdir('aaa')
Traceback (most recent call last):
File "", line 1, in 
OSError: [Errno 17] File exists: 'aaa'
>>> print os.listdir('/')
['media', 'root', 'sbin', 'usr', 'lib', 'tmp', 'home', 'var', 'cdrom', 'etc',
 'rofs', 'bin', 'boot', 'dev', 'initrd.img', 'mnt', 'opt', 'proc', 'srv',
 'sys', 'vmlinuz']

These is just a brief tutorial about sys and os modules.

Wednesday, May 19, 2010

The beauty of Python: Simple functions - part 1

Validation of a condition and return result in 'Yes' or 'No'.

>>> def valid(x,y):
...     return ('Yes' if x==y else 'No') 
... 
>>> valid(2,3)
'No'
>>> valid(2,2)
'Yes'


Some usefull functions from string module .

>>> import string 
>>> var_template_string=string.Template(" The $subj $vb $something")
>>> var_template_string.substitute(subj="PC", vb="working", something="now")
' The PC working now'
>>> some_string_dictionary={'subj':'car', 'vb':'is', 'something':'blue'}
>>> var_template_string.substitute(some_string_dictionary)
' The car is blue'
>>> some_string_dictionary


Some example with re module and html tag

>>> import re
>>> t='<p>'
>>> some_tag = re.compile(r'<(.*?)(\s|>)')
>>> m = some_tag.match(t)
>>> print m
<_sre.SRE_Match object at 0xb7f79da0>
>>> dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start']
>>> print m.start()
0
>>> print m.groups()
('p', '>')
>>> print m.group()
<p>
>>> print m.span()
(0, 3)

The re module has many usefull functions.
This is just some examples to show the simplicity of python language.

Monday, March 1, 2010

Python and OpenGL - first steps

First you need to install python .
Second you need to install pyopengl module.
This is easy if we use some linux distributions.
On Fedora we can use command yum.
On Debian and Ubuntu we can use apt-get.
At last we need some basicaly examples.
We can get some examples from:PyOpenGL-Demo
But this is not all we will need more.
To go on next step we will need to read OpenGL specifications.
Try to use search on internet to see more about OpenGL.

Tuesday, February 23, 2010

How to display the "%" in python ?

I saw something interesting on the internet.
How to display the "%" in python.
I found so far two methods:


>>> print "See %d%%" % (0.77 * 100)
See 77%
>>> print "See {0:.0%}".format(0.77)
See 77%
>>>

Friday, February 12, 2010

Where is Santa Claus?

I wrote a python module. I called it "geo" because it is a geographic module.
The funny stuff is when i use it with "Santa Claus".

>>> import geo
>>> geo.adress("Santa Claus")
{'status': '200', 'latitude': '32.1715776', 'longitude': '-82.3315138', 'accuracy': '4'}

So where is Santa Claus ?!
Google Maps API should be prepared to respond.
Tomorrow a child will know how to use the Python language.
Who knows ...