"""
This python script read the name of image and will create a new image with the given width and height.
$ python imgresz.py
filename input image:test.png
test.png
filename output image:test-out.jpg
->width:500
->height:400
"""
import os
import sys
from PIL import Image
from PIL import ImageDraw
filnaminp=raw_input("filename input image:")
filnamout=raw_input("filename output image:")
w=input("->width:")
h=input("->height:")
imgi=Image.open(str(filnaminp))
imgo=imgi.resize((w,h),Image.BILINEAR)
imgo.save(str(filnamout))
Is a blog about python programming language. You can see my work with python programming language, tutorials and news.
Monday, April 30, 2012
Resize screenshot with PIL python module .
Saturday, April 7, 2012
When to use '__main__' ?
python your_script.py
all of the code that is at indentation level 0 gets executed and functions and classes that are defined but none of their code gets ran.
If will then read :
if __name__ == '__main__'
so it will execute the block standalone.
In other words, when you use the __main__ this means the module is being run standalone
if __name__ == '__main__':
print '... is being run by itself'
else:
print '... is being run directly'
Sunday, February 26, 2012
The wx module - tutorial 02 - class and button function
In this tutorial I will show how to use wx using one class example.
This tutorial is based on some code from a previous tutorial.
Let's see the source code:
import wx
class my_gui_form(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Example windows wx with Python',size=(300,150))
wx.StaticText(self, -1, 'User', (10, 20))
user = wx.TextCtrl(self, -1, '', (110, 20), (160, -1))
wx.StaticText(self, -1, 'Password', (10, 50))
passwd = wx.TextCtrl(self, -1, "", (110,50),(160, -1), style=wx.TE_PASSWORD)
conn = wx.Button(self, -1,'Connect',(10,80),(260, -1))
conn.Bind(wx.EVT_BUTTON, self.onButton)
def onButton(self, event):
button = event.GetEventObject()
print "The button's label is: " + button.GetLabel()
print "The button's name is: " + button.GetName()
if __name__ == "__main__":
app1 = wx.App(False)
frame = my_gui_form()
frame.Show()
app1.MainLoop()
First , I make a class named my_gui_form.
Also I add the self on each function from this class.
I make the onButton function to working with the button Connect.
I read the event of the button with event.GetEventObject.
The link with this function is make by:
conn.Bind(wx.EVT_BUTTON, self.onButton)
Source Code Optimization:
The -1 from is can replace with wx.ID_ANY.
Thursday, February 23, 2012
The wx module - tutorial 01
Install wx python module using root account.
# yum install wxPython.i686
The most simple example is show bellow.
$python
Python 2.7.2 (default, Oct 27 2011, 01:36:46)
[GCC 4.6.1 20111003 (Red Hat 4.6.1-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>> app1=wx.App()
>>> frame=wx.Frame(None,-1,'Example windows wx with Python')
>>> frame.Show()
True
>>> app1.MainLoop()
>>>
Let's see the result of this python script:
Let's take a look at the source code.
import wx
This line of code allows us to use wx python module.
app1=wx.App()
This line defines our application named app1.
A frame is a window whose size and position can be changed by the user.
Let's see:
frame=wx.Frame(None,-1,'Example windows wx with Python')
frame.Show()
Finally, processing and display function in main function.
app1.MainLoop()
Bellow, we can see a more complex example, where we find : labels , two editbox and one button.
The event-processing function button has not been implemented.
import wx
app1=wx.App()
frame=wx.Frame(None,-1,'Example windows wx with Python',size=(300,150))
wx.StaticText(frame, -1, 'User', (10, 20))
user = wx.TextCtrl(frame, -1, '', (110, 20), (160, -1))
wx.StaticText(frame, -1, 'Password', (10, 50))
passwd = wx.TextCtrl(frame, -1, "", (110,50),(160, -1), style=wx.TE_PASSWORD)
conn = wx.Button(frame, -1,'Connect',(10,80),(260, -1))
frame.Show()
app1.MainLoop()
Let's see the result of this python script:
I will illustrate how this working in a future tutorial.
Saturday, November 26, 2011
Simple socket client with python
This example was presented in a previous post named Simple socket server with python.
The program is simple, the algorithm uses connection and some data processing input from the console.
I used the same test method as for the program created in C + +.
The program breaks the connection when the client enter: end connection
Here's the source code:
import socket
import sys
HOST = 'your-IP'
PORT = 5001
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
s = None
continue
try:
s.connect(sa)
except socket.error, msg:
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
sys.exit(1)
data=''
while data<>'end connection':
data=raw_input()
s.send(data)
data = s.recv(1024)
s.close()
print 'Received', repr(data)
Sunday, November 20, 2011
Simple socket server with python
I can not say that it really is a server that does not accept multiple connections.
The script worked stable sending manually entered text.
I not checked the stability for the large data streams.
It is also normal because as you see below is just one example.
import socket
HOST = 'your-IP'
PORT = 5001
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn,addr=s.accept()
print 'Conectat la =',addr
while 1:
data = conn.recv(1024)
if not data :
break
conn.send(data)
print data
conn.close()
The distance between me and the server was considerable.
Tuesday, October 25, 2011
The python module : spynner
Spynner is a stateful programmatic web browser module for Python with Javascript/AJAX support based upon the QtWebKit framework.The module is esay to use. With few lines of codes you can use this module to parse ,view and use web pages.
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import re
import spynner
from BeautifulSoup import BeautifulSoup
import time
br = spynner.Browser()
br.create_webview()
br.show()
br.set_html_parser(BeautifulSoup)
br.load("http://www.linuxtoday.com/")
br.fill("input[name=username]", "name")
br.fill("input[name=passwd]", "pass")
#br.simulate_click("input[name=submit]",True)
#br.select("IBESNA~US")
#br.select('option[value="IBESNA~US"]')
#br.wait_page_load()
br.browse()
The result is show in the image bellow:
The source code is not complete. I make this simple example just to show us how to fill some editbox.
If you wantthen you can develop this script and make more useful.
I wait your answers with source code additions and new ways of using this python module.
Saturday, October 1, 2011
Show photo albums and storage with python and gdata module
First I use module getpass and i connect to google user account.
Next I use gdata functions to print user albums and spending storage.
You can also use the gdata module to add comments, rotate photos, add photos ...
The code source is show bellow:
import getpass
import gdata.photos, gdata.photos.service
pws = gdata.photos.service.PhotosService()
username=raw_input("username - ")
password= getpass.getpass("password - ")
pws.ClientLogin(username, password)
#get all albums from account
userfeed_albums = pws.GetUserFeed(kind='album')
#print albums
print "User %s has these albums: %s" % (userfeed_albums.user.text,
[a.title.text for a in userfeed_albums.entry])
#print storage
print "%s is spending %s-Mb on storage" % \
(userfeed_albums.nickname.text, int(userfeed_albums.quotacurrent.text)/1024/1024)
Sunday, September 25, 2011
Tips and tricks with Python ...
The modules come with many features that are not fully documented.
Some of them we do not know.
We can use the dir function, but in most cases the result is a huge list.
Here is a simple detection method.
$ python
Python 2.7.1 (r271:86832, Apr 12 2011, 16:16:18)
[GCC 4.6.0 20110331 (Red Hat 4.6.0-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gnome
>>> dirlist=dir(gnome)
I put content above command in a list.
We need to processed now.
>>> dirlist.index('ui')
Traceback (most recent call last):
File "", line 1, in
ValueError: 'ui' is not in list
>>> dirlist.index('sound_play')
118
Here I found an item. To know something about it.
>>> help(dirlist[118])
no Python documentation found for 'sound_play'
Nothing about this. Let's use the command dir.
>>> dir(dirlist[118])
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Using the examples above, you can create a script to parse this source code and check if the functions are the same as our version.
Saturday, September 24, 2011
Creating folders and documents with gdata module
The problem that I solved it:
creating folders and documents in your Gmail account.
First you need to install gdata module.
In fedora I used:
yum install python-gdata.noarch
Here are the first lines of source code that creates a folder named test-fedoraPython 2.7.1 (r271:86832, Apr 12 2011, 16:16:18)
[GCC 4.6.0 20110331 (Red Hat 4.6.0-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gdata.docs.service
>>> my=gdata.docs.service.DocsService()
>>> my.ClientLogin('your-account@gmail.com','your-password')
>>> my.CreateFolder('test-fedora')
I tried to automate the process of creating folders and I used a list and instruction for>>> folders=['aaa','bbb','ccc']
>>> for f in folders:
... my.CreateFolder(f)
...
To create a document to write more lines of code.This is because there are many types of documents
>>> new_entry = gdata.GDataEntry()
>>> new_entry.title = gdata.atom.Title(text='fedora-test')
>>> category = my._MakeKindCategory(gdata.docs.service.DOCUMENT_LABEL)
>>> new_entry.category.append(category)
>>> created_entry = my.Post(new_entry, '/feeds/documents/private/full')
Here's a simple solution to avoid loss of mail password.>>> import getpass
>>> username = raw_input('Please enter your username: ')
Please enter your username: user1
>>> password = getpass.getpass()
Password:
>>> print username
user1
>>> print password
pass1
I hope you will use this
Friday, August 12, 2011
GLUT - Creating a fullscreen applications.
glutGameModeString()
glutEnterGameMode()
Below is the source commented.
import sys
from OpenGL.GL import *
from OpenGL.GLUT import *
def main():
# Initialize OpenGL
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
# Configure the display output
glutGameModeString("1024x600:32@60")
# The application will enter fullscreen
glutEnterGameMode()
# Setup callbacks for keyboard and display
glutKeyboardFunc(keyboard)
glutDisplayFunc(display)
# Enters the GLUT event processing loop
glutMainLoop()
def keyboard(key, x, y):
if key == 'q':
sys.exit(0)
def display():
glClear(GL_COLOR_BUFFER_BIT)
# Draw a green line
glBegin(GL_LINES)
glColor3f(0.0,100.0,0.0)
glVertex2f(1.0, 1.0)
glVertex2f(-1.0, -1.0)
glEnd()
glutSwapBuffers()
if __name__ == "__main__":
main()
Thursday, August 11, 2011
How to make working pygtk with python 2.7
A good start to use this module:
Articles
I do not know if I presented this module on the site, but now I will try to present it.
First, as it says on the official site:
"PyGTK lets you easily create applications with a graphical user interface Using the Python programming language."
The second time is easy to use because we can easily create interfaces using Glade.
Glade is a RAD tool.
This development tool to let us create user interfaces for the GTK + toolkit and the GNOME desktop environment.
The output is an xml file which is then used by PyGTK.
Read more on the official site: Glade RAD tool.
The tricky part is connecting with the python source code from the XML components.
You can download it here and install version 2.22 on Windows from here.
I use pygtk-all-in-one-2.22.6.win32-py2.7.msi to test pygtk.
Also, you need GTK 2.22 from here.
How to make working Python 2.7 with GTK?
Just right-click on My Computer, then select Properties.
Click the Advanced tab in the dialog that pops up, and click the Environment Variables button near the bottom.
Under System variables, click the New button and enter GTK_BASEPATH.
Now under variable named Path, and click the Edit button and add GTK_BASEPATH\bin;.
Click the OK buttons restart Windows XP.
Now it is working fine with Python 2.7.
Let's try this script:
#!/usr/bin/env python
import sys
try:
import pygtk
pygtk.require("2.0")
print "pygtk 2.0 ok!"
except:
print "pygtk 2.0 BAD!"
pass
try:
import gtk
print "gtk ok!"
except:
print "gtk BAD!"
pass
GLUT - teapot
GLUT (pronounced like the glut in gluttony) is the OpenGL Utility Toolkit, a window system independent toolkit for writing OpenGL programs. It implements a simple windowing application programming interface (API) for OpenGL. GLUT makes it considerably easier to learn about and explore OpenGL programming. GLUT provides a portable API so you can write a single OpenGL program that works across all PC and workstation OS platforms.To work you need to install Python (I used version 2.7) and how PyOpenGL. You'll find it here.
The python module PyOpenGL provides bindings to OpenGL, GLUT, and GLE.
The necessary steps are:
1. initialize the GLUT library :glutInit function
2. sets the initial display mode with parameters set GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH
3. initialization of the future windows with a given width/heightat a given width/height
4. Then the creation of four functions required to display, resizing, keyboard and display.These functions will be called in order to: glutCreateWindow, glutReshapeFunc, glutKeyboardFunc, glutDisplayFunc.
5. calling these functions.
6. calling glutMainLoop to enter the GLUT event processing loop.
Here's source code.
import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def display():
glEnable( GL_LIGHTING )
glEnable( GL_LIGHT0 )
glEnable( GL_DEPTH_TEST )
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )
glPushMatrix()
gluLookAt( 0,2.5,-7, 0,0,0, 0,1,0 )
glutSolidTeapot( 2.5 )
glPopMatrix()
glFlush()
def reshape(w,h):
glViewport( 0, 0, w, h )
glMatrixMode( GL_PROJECTION )
glLoadIdentity()
gluPerspective( 45.0, 1.0*w/h, 0.1, 100.0 )
glMatrixMode( GL_MODELVIEW )
glLoadIdentity()
def keyboard(key,x,y):
if key==chr(27): sys.exit(0)
glutInit( sys.argv )
glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH )
glutInitWindowSize( 500, 400)
glutCreateWindow( 'teapot' )
glutReshapeFunc( reshape )
glutKeyboardFunc( keyboard )
glutDisplayFunc( display )
glutMainLoop()
Here's the result.You can read more in the documentation.