analitics

Pages

Tuesday, April 19, 2011

Things that prevent complications ... part 1

The difference between ... input and raw_input
input returns an object that's the result of evaluating the expression. raw_input returns a string ...

The difference between ... Python 3 and Python 2
If you run the Python 3, do not use sample code written for Python 2, you'll just end with many errors and much confusion ...

The difference between ... extend and append on a list
Extend just extend a list with another list by adding each element on list, append add the list like one element...

The difference between ... function and method
Method is a function with an extra parameter which is the object that it's to run on...

The difference between ... deleting a variable and deleting its contents
By removing its contents by setting NoneType variable allows you to add a new value.

These are just a few differences, in reality they are much more ... I will return with others ...

Saturday, April 16, 2011

PyOpenGL and PyOpenGL-accelerate 3.0.1 - latest version

First , the major error is this:
I try fix this with ... NetFx20SP2_x86.exe, not working.
I use google to donload the dll file. Is not correct way , but this fix error.
I use this PyOpenGL-3.0.1.zip to install OpenGL module under Python 2.6.2 ...
Just use this :
python setup.py install
But you can not use python on command line, because you need to add on enviroment vars...
Just try something like this...
C:\>set PATH=C:\Python26;%PATH%
To see the result , just use:
C:\path
You can test the OpenGL modules...
>>> import OpenGL
>>> import OpenGL_accelerate
>>> help(OpenGL_accelerate)
Help on package OpenGL_accelerate:

NAME
    OpenGL_accelerate - Cython-coded accelerators for the PyOpenGL wrapper

FILE
    c:\python26\lib\site-packages\opengl_accelerate\__init__.py

DESCRIPTION
    This package contains Cython accelerator modules which
    attempt to speed up certain aspects of the PyOpenGL 3.x
    wrapper mechanism.  The source code is part of the
    PyOpenGL package and is built via the setupaccel.py
    script in the top level of the PyOpenGL source package.

PACKAGE CONTENTS
    arraydatatype
    errorchecker
    formathandler
    latebind
    nones_formathandler
    numpy_formathandler
    vbo
    wrapper
-- More  --
This is all .

Logging documentation for Python 2.7 reorganised like Python 3

First , what is logging module ?
This module defines functions and classes which implement a flexible event logging system for applications and libraries.
The organisation is now as follows:
  • http://docs.python.org/library/logging – reference documentation for the logging module
  • http://docs.python.org/library/logging.config - reference documentation for the logging.config module
  • http://docs.python.org/library/logging.handlers - reference documentation for the logging.handlers module
  • http://docs.python.org/howto/logging – basic and advanced logging tutorials
  • http://docs.python.org/howto/logging-cookbook – how to use logging in different scenarios
The best way to understand this module is to see the tutorials...

Thursday, April 7, 2011

Using modules in Python 3.2

Python is quite known and appreciated.
Today I saw an article "What's your favorite programming language?" LinuxWeek proncetaj of a 26% (1074 votes) ...
In python "module" which is actually a library.
Using it is simple: import "module name"
See example below:

import os
There are many modules in the Python language.
For example I chose an example of how to display modules that are installed. Open the python command line and run the examples below:

C:\Python32>python
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> help('modules')

Please wait a moment while I gather a list of all available modules...

__future__          audioop             imp                 shlex
_abcoll             base64              importlib           shutil
_ast                bdb                 inspect             signal
_bisect             binascii            io                  site
_codecs             binhex              itertools           smtpd
_codecs_cn          bisect              json                smtplib
_codecs_hk          builtins            keyword             sndhdr
_codecs_iso2022     bz2                 lib2to3             socket
_codecs_jp          cProfile            linecache           socketserver
_codecs_kr          calendar            locale              sqlite3
_codecs_tw          cgi                 logging             sre_compile
_collections        cgitb               macpath             sre_constants
_compat_pickle      chunk               macurl2path         sre_parse
_csv                cmath               mailbox             ssl
_ctypes             cmd                 mailcap             stat
_ctypes_test        code                marshal             string
_datetime           codecs              math                stringprep
_dummy_thread       codeop              mimetypes           struct
_elementtree        collections         mmap                subprocess
_functools          colorsys            modulefinder        sunau
_hashlib            compileall          msilib              symbol
_heapq              concurrent          msvcrt              symtable
_io                 configparser        multiprocessing     sys
_json               contextlib          netrc               sysconfig
_locale             copy                nntplib             tabnanny
_lsprof             copyreg             nt                  tarfile
_markupbase         csv                 ntpath              telnetlib
_md5                ctypes              nturl2path          tempfile
_msi                curses              numbers             test
_multibytecodec     datetime            opcode              textwrap
_multiprocessing    dbm                 operator            this
_pickle             decimal             optparse            threading
_pyio               difflib             os                  time
_random             dis                 os2emxpath          timeit
_sha1               distutils           parser              tkinter
_sha256             doctest             pdb                 token
_sha512             dummy_threading     pickle              tokenize
_socket             email               pickletools         trace
_sqlite3            encodings           pipes               traceback
_sre                errno               pkgutil             tty
_ssl                filecmp             platform            turtle
_string             fileinput           plistlib            turtledemo
_strptime           fnmatch             poplib              types
_struct             formatter           posixpath           unicodedata
_subprocess         fractions           pprint              unittest
_symtable           ftplib              profile             urllib
_testcapi           functools           pstats              uu
_thread             gc                  pty                 uuid
_threading_local    gdata               py_compile          warnings
_tkinter            genericpath         pyclbr              wave
_warnings           getopt              pydoc               weakref
_weakref            getpass             pydoc_data          webbrowser
_weakrefset         gettext             pyexpat             winreg
abc                 glob                queue               winsound
aifc                gzip                quopri              wsgiref
antigravity         hashlib             random              xdrlib
argparse            heapq               re                  xml
array               hmac                reprlib             xmlrpc
ast                 html                rlcompleter         xxsubtype
asynchat            http                runpy               zipfile
asyncore            idlelib             sched               zipimport
atexit              imaplib             select              zlib
atom                imghdr              shelve

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

>>> dir('module')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt_
_', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__'
, '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__
rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
 'capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'f
ormat', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'is
identifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupp
er', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'r
find', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines
', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> exit()
This is just another example of how to use python.

Friday, March 25, 2011

PyGUI 2.4 is available from

PyGUI is a cross-platform GUI toolkit designed to be lightweight and have a highly Pythonic API.
It's works with Python 3 on MacOSX and Windows.
You use the OpenGL facilities but you will need PyOpenGL and GtkGLExt and PyGtkGLExt.
Official site is here.
In this image you can see some controls created with PyGUI.

Tuesday, March 22, 2011

Python Tools for Visual Studio

I just read that python will be placed in the tools in Visual Studio.
This can only be good news for the python community.
More about this here.

Monday, March 21, 2011

The discovery of an ancient ancestors linux ...

Who says penguins are weak?
Linux is a good system if it is used by smart people.
Since ancient times people are born with penguins.
It seems that dinosaurs could not survive, but the Penguins have managed well.
They became smaller but everyone loves them.
Whether they are small and fast as gentoo, or slower ... we are glad that we have no windows open.
More infos here.

Monday, March 14, 2011

IronPython released on 12 and updated on 13 march.

What is it?
IronPython is an implementation of the Python programming language and is running under .NET and Silverlight.

How does it work?
When you run a .NET program written in a language such as C# or VB.NET, your code gets compiled to Intermediate Language (IL) code.
IronPython contains the code and classes for IronPython itself, including the IronPython interpreter. When you run the IronPython interpreter, you are running the IL code for IronPython itself.
More simplistic, the classes you create in your Python code are created dynamically at runtime.

What's New?
This release numerous bug fixes, also includes a IronPython Tools for Visual Studio, support for extension methods and more...
You can see more on official site.

Saturday, March 12, 2011

Tutorials from PyCon 2011

PyCon 2011 is held from March 9th through the 17th, 2011 in Atlanta, Georgia.
It is the annual Python community conference.
More on this page:Pycon 2011 tutorials

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