Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, September 3, 2011

PyQt: power of Python, beauty of Qt

Qt is very powerful tool for GUI programming. But programming using Qt C++ is not always easy because of unavailability of libraries and difficulty in coding. But Python is powerful and has abundant list of libraries related to virtually anything. Some operations in Python is very easy to use. But the problem of Python is that, it has no GUI its own as handy. PyGTK (Python and GTK) and PyQt (Python and Qt) are the remedy. Here I am explaining how to start with PyQt.
PyQt has no support from QtCreator yet, but the features of QtDesigner can also be used for the PyQt coding. This tutorial explains how to start PyQt programming if you are already aware of Qt C++ programming. This is not just a 'hello world' program, but the code will do something and make you capable of coding your own programs.
In this example, we are building a simple GUI with three LineEdit bars and a single button. When the button is clicked, the numbers entered in the LineEdit a and b are added and the sum is shown in the third LineEdit.


First of all, make GUI widget in Qt Designer and rename the objects a, b, sum and pushButton as shown in screen-shot below. Also make a custom slot named calc_sum(). Save and quit the Designer program.


Now you can see the user interface file named 'widget.ui' (the filename may vary if you changed the widget name while creating your project. Anyway, the filename with .ui as extension is the file we need). We need to create the curresponding python file for user interface. In C++, it is done using uic(User Interface Compiler). In our case, in python, we use a utility named 'pyuic4'. If 'pyuic4' will be automatically installed while you install PyQt. If not, especially in Linux, install it from the repository. Then make the user interface file 'calc_ui.py' (or any name you wish. But for the first time use this name to avoid ambiguity) file using the command:

pyuic4 widget.ui > calc_ui.py

This command will generate a new file named 'cal_ui.py'. This is the user interface file only. We are going to make another file 'calc.py' which will handle the core program. Use a text editor and copy the code below:

import sys
from PyQt4 import QtCore, QtGui

from calc_ui import Ui_Widget


class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Widget()
        self.ui.setupUi(self)
    def calc_sum(Widget):
    value1=Widget.ui.a.text();
    value2=Widget.ui.b.text();
    result=float(value1)+float(value2);
    str_result=str(result)
    Widget.ui.sum.setText(str_result);


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())

Save the file. Then run the file:

pyhon calc.py
I am not so good in explaining the code. I think you got the idea of how to make a custom slot and to make a standalone program. If any reader need clarification or more explanation, I will try to explain further.

Saturday, June 11, 2011

One day PyBrain came to power....

Recently, I went straight away to PyBrain and found it is useful to AI researchers and enthusiasts. Python rocks once again. PyBrain is a modular library for python. As far as PyBrain developers is concerned, it is Python Based Reinforcement Learning, Artificial Intelligence and Neural Network Library. PyBrain is opensource and it is licensed under BSD software license.
PyBrain simulates neural networks inside our brain in a computer. Once you created the neural networks, you need to train it for a particular task. Sometimes training of more than thousand times is required to properly get done it's job. Sometimes, training will be frustrating especially when you didn't give proper degree of freedom to the neural network structure. However, I found pyBrain interesting.
It is good idea to start with pyBrain documentation. In the beginning of the tutorial, they provide a simple example of training for an X-OR gate. But it will take a lot of training steps to work properly. But for the same neural network structure, if you are trying to simulate an AND gate or an OR gate, you probably get everything done.

Tuesday, January 12, 2010

Online Python

My friends always complaint that they don't have an environment for learning python. They have internet connectivity in the college, but not having the permission to install python interpreter on those machines. So they satisfied by just reading the tutorial only and not by doing python. But here is the solution. Online Python Interpreter is an online python terminal and you can enter python commands as like in your shell. The virtual browser shell is a little bit slower and and again slower for slower internet connections. The speed is entirely depend upon your internet connection and no way to increase because entire python engine is on the server side. But I am sure it will be a boon for the beginners and net-book users. Current limitations are:
  • Can't define functions or classes.
  • Can't run a script

Click to enter online python interpreter
Click to view the ubuntu forum discussion about online python interpreter

Friday, January 1, 2010

PYRO : Python in hand with Robotics

Python developers all over the world are searching for fields that are not involved python. I recently found a good job by them - a boon for robotics enthusiasts - that is Python Robotics or simply Pyro.

Go to pyro project page

Download Pyro live CD

Many built-in python scripts are there to define the robotic brain and paths. Of course, you can write your own scripts. Anyway, pyro is a wonderful experience.

I encountered a problem while booting from pyro live CD. It seems to be mother board and chipset specific. My problem was, no x start up. It hangs up when displays "Probing/Loading AGP Modules...". I used several knoppix cheat codes to enter into kde desktop. It was successful. Thanks to knoppix developers forum. The boot time cheat code i entered is:

knoppix noagp

If you encounter any such problem, try to search for knoppix boot problems and not for pyro boot problems.

Tuesday, December 8, 2009

Go on with pyS60

I got a very good feedback from my previous post: "How to simulate PyS60 in your PC". As the request of opentechlab readers, I am attempting to write a brief beginner level tutorial on pyS60 emulator.

Once you are successful in installing and setting up the environment (If you didn't set up yet, click here), it is the time to go on.

Start the emulator program from:

Start->All programs -> S60 Developer tools -> 3rd edition FP2 SDK -> v1.1 -> Emulator

You probably need to wait for a couple of seconds to load it if your system is slow. Then a medium sized window with a full fledged mobile phone appears on the screen.

Now you need to open python. Just do as in your mobile phone. it's in Menu -> Installations -> python.

Now it's ready and do what you want.

Hacking python script

Select options -> Run script ->ball.py

You can move the ball anwhere in the screen. It's a physics simulation example in python. You can see the actual python script by opening ball.py file using any editor (notepad is not recommended. programmers notepad is good). The file is stored in :

C:\S60\devices\S60_3rd_FP2_SDK_v1.1\epoc32\winscw\c\python

Search for the word 'blobsize'. Then you can find a line like:

blobsize = 16

Change the value of blobsize into 25 and save it. Then open ball.py in emulator. Did you notice any change? Similarly you can change acceleration, gravity (what about changing gravity into -0.01 ?) etc.

Developing your own programs

I am just starting with a hello world. Here is the program.

1)Simple hello world

print "Hello World!"

2)Say, hello world

from audio import*

say("Hello World!")

3)graphical hello world!

import appuifw
appuifw.note(u"Hello World!", "info")

It is good practice to make a short cut of python on the mobile desktop by changing options in settings.

Monday, December 7, 2009

How to simulate PyS60 in your PC

You can do your experiments in PyS60 without touching your mobile phone. The experimentation is easy while you set up everything in your PC. Here I am explaining how to set up the PyS60 environment in WinXP platform. I didn't try this attempt on my Linux yet. I will surely post about it if I get some good mobile stuff on Linux. This will be a boon for python developers in Nokia S60 mobile phones. But rarely it can be seen that some python scripts works neatly on simulator may cause strange responses on your real world system. I would like to here about it if you get any funny experience on your S60 device.
Download the required things:

1)Download S60_3rd_Edition_SDK_Feature_Pack_2_v1_1_en.zipfrom the following link:
http://www.forum.nokia.com/info/sw.nokia.com/id/807ec36d-0a8e-4bda-8e10-4d5e5bb4764a/S60_3rd_Edition_SDK_Feature_Pack_2_v1_1_en.zip.html


2)You can find ActivePerl 5.6.1 build 635 here:
http://downloads.activestate.com/Act...SWin32-x86.msi

3)Download PythonForS60 _1_4_5_SDK_3rdEdFP1.zip from http://sourceforge.net/projects/pys60/files/

First install ActivePerl because S60 SDK requires it.
Then install S60 SDK. Please note to install it in C:\ drive to avoid confusion.
Extract PythonForS60_1_4_5_SDK_3rdEdFP1.zip. Then you get another archived file sdk_files.zip.
Extract it again and you get a directory named 'epoc32'.
Copy this directory into "C:\S60\devices\S60_3rd_FP2_SDK_v1.1"
Then probably Windows XP asks to replace the already existing folder 'epoc32'. Click yes.
You have done. Cheers!

Monday, August 31, 2009

Bluetooth interactive console using pyS60

Nowadays, text messages via mobile phones are shortening to small, but difficult to understand language. I don't think whether the major reason behind this shortening is economic, but most people feel tedious to type text through a 4*3 panel. Typing a program like, C or python in correct syntax is again a tedious work. You can use bluetooth console, in order to avoid this problem effectively. Here I describe how to setup bluetooth consloe communcation in your MS Windows XP platform. For beginners, this procedure may feel ambigous. So I tried my maximum to describe it with screenshots.

If you are not aware of pyS60 please read this.

You can find some other tutorials here:
s60python
nokia wiki
pys60 Library Referance
Yet another tutorial
Lecture

The above links were extremely useful to me. The procedure is repeated here, but I tried to describe it in rather simple way. If you feel any difficulties, please inform me.

Setting up bluetooth interactive console in winXP

step1: Plug your bluetooth device into your PC (any USB port). Then Run your bluetooth driver program which you installed from the CD/DVD when you buy your bluetooth dongle.
Then automatically a serial port is assigned for it. In my PC, it is COM6. You can do step 5 in case you don't know the COM port your PC supported.

step2: Run command 'hypertrm' in your run window. Run window can be opened by clicking Run option from the start menu.

step3:You will get hyperterminal opened like this:

Enter any valid name for your connection and select a suitable icon and forward.

step4:Then you will get another box like this:

Type any 3 digit area code and phone number.Your country or region may be automatically filled. If not, do it manually. Select COM6 from 'connection using' lineEdit tab. It may be changed. You will get which COM port your computer assigned (If you didn't get it, notice first screenshot)

step5:Take your symbian smart phone with pys60 installed. Turn your bluetooth ON and open pys60 application. From 'options' menu, select 'bluetooth console'. Your application then searches for blutooth device. You can optionally select it as your default connection.

step6 (Error Debugging): You are now probably connected successfully. Not yet? Check your connections. Check whether you run your bluetooth driver.If your bluetooth driver is running, a symbol of bluetooth will appear on the panel (see screenshot 1). I used Enter blutooth dongle (part number:E-UBTV) from entermultimedia. and it's driver(BlueSoleil). The driver is downloadable in case you lost the CD/DVD with your dongle. If you can type anythong on the white blank screen of hyperterminal, you are probably done everything. Else, you should check the whole procedure.
In any case, you should plug out the dongle and replug.
Didn't connected yet? Some mysterious powers are playing around you ;-)
I am happy to help if you can't find any way to connect.


step7: If you are successful in connecting your mobile, you are done.

step8:You can do anythong with python. Try these

step9: While you close application, you get a dialogue box and click yes.

You can save hyperterminal settings for the future use. Then when you run 'hypertrm' command, you will get a window like screenshot 2. simply close the box named 'Connection Description' and then you can open the saved file (here, pybluetooth.ht). Again there is an option to save the connection in your mobile and make it as default connection.

Sunday, July 26, 2009

Parallel port programming using python

Setup parallel port in linux (Debian/Ubuntu)
You should have installed python on your distro. You must have the previlages of 'su' to do the following installation

# apt-get install python-parallel
# rmmod lp
# modprobe ppdev
# python

>>> import parallel
>>> p = parallel.Parallel()
>>> p.setData(0xFF)


Assuming you have some basic python knowledge. If you didn't install pyhton -parallel, you can't import parallel. Now p.setData(oxFF) sets every outputs of parallel port to ON. Try different values instead of 0xFF. (To do this you require basic knowledge of hexadecimal representation of binary numbers). Try this chaser program.

x=[1,2,4,8,16,32,64,128]
while(1):
for i in x:
p.setData(0xFF)
time.sleep(2) #Good night for 2 seconds


The program will work until you force to quite python or an unexpected UPS failure. That may be funny ;-) But Intentionally did that for the program simplicity.

No Linux? Windows only? :-( Just try it out

There is nothing to do in windows. Download latest python first. Install it. Then download pyparallel for windows fron sourceforge. Install it Now everything OK. Open python either by command or open IDLE (It will be installed with python core in windows). Then type the following:

>>> import parallel
>>> p = parallel.Parallel()
>>> p.setData(0xFF)


The example chaser program is also applicable for windows platform.

Read my post on parallel port programming in C/C++

Wednesday, July 22, 2009

Teach your computer how to speak!

It is good idea to teach computer to speak!. There a number of programs available for winXP paltform, but here is a unique program "espeak" for your linux. Just enter the command in terminal,

$espeak "Boss, I can speak now"

will work fine. It is useful for some scripts in linux to remind some status of computer to the user like a personal assistant. espeak is not an internal bash command and need to be installed. I simply installed in my Debian from repository.

#apt-get install espeak


The command above will work well with ubuntu systems also. If you are using any other distro, you need to download and install it manually. Click here to know more.

Here is a simple python program which uses espeak as system command. To use it you require python and espeak installed.

#! /usr/bin/python
# File: speak.py

import os
from Tkinter import *

class App:

def __init__(self, master):

frame = Frame(master)
frame.pack()
self.button = Button(frame, text="Click", command=self.activate)
self.button.pack(side=LEFT)


def activate(self):
os.system('espeak "Boss, I can speak now"')
print "Boss, I can speak now"

root = Tk()

app = App(root)

root.mainloop()

Just copy the above program into a new file named speak.py and 'cd' into the directory and enter,

python speak.py


You are free to use this program anywhere since espeak is under GPL.

Saturday, June 13, 2009

Python for Symbian s60


Python is very convinient language compared to any other and constantly increasing it's popularity. It is listed in the top 10 programming languages also. It can be used in MS Windows, Linux and everywhere. It's a best hacker's choice also. Many varieties are emerging from python. Portable python- which need not be installed but paste the file in your Thumb drive or any other portable devices and you can use it everywhere. Really Nice. Now the pyhton coming to conquer the mobile phone world!. Yes, you can do what is you go for in a PC.

  • Just donwlad the pyhton instllalble file. Install it
  • Open python for s60
  • Options->Interactive Console
  • Do what you want
  • You can see some example *.py files in Options->Run Script
simplest example:

print "hello World!"

#Note: Wherever you want to press enter in PC version of linux, in mobile, you use 'scroll key', not 'enter' character in the list of special characters. You can run python scripts also bu require one text editor. One good text editor is JtextLite.

Happy Programming!

Friday, June 12, 2009

Play with "cdrom" in Linux

Linux comand shell "bash" is powerful as we know. Here is a fun with bash. You can control your cdrom using 'eject command'. Here is only a simple description. For nore details, you should look at it's man pages.

This is not a project or something serious. just for fun. You can control your cdrom by using this code. This will only work on Linux platform. I did it in fedora core 9. But it will work other disro's also.

!!!!!!!WARNING!!!!!!!!
1)Some procedure described in this article is not a recommended or the hardware devices are intended to work like it. Do it in your own risk.
2)Don't interrupt the way the hardware working (the movement of CD ROM tray by your hand).

Open your 'cdrom' tray under software control
Try this command

$eject cdrom


It will try to open your cdrom tray. if you have two or more cdrom drives, try

$eject cdrom0


If you havn't any cdrom device, bash will return an error message:

$eject cdrom2
eject: unable to find or open device for: `cdrom2'


You can find your device name ( "cdrom0', 'cdrom1' etc.) from "/media"

Close your 'cdrom' tray under software control
Try this command

$eject -t cdrom


Other useful parameters are there in 'eject'. You can read about it:

$man eject


Writing a bash script
Just entering the command at a time is not convenient. You can write some commands together and execute it when you want.
Open a new file using gedit editor (or any other you want)

$gedit cdromplay


A winow will appear and type what you want. For example, if you want to open and close your cdrom continously three times just print like this:

eject cdrom
eject -t cdrom
eject cdrom
eject -t cdrom
eject cdrom
eject -t cdrom


save it and close.
Then to resolve permission,

$chmode +x cdromplay

Then execute cdromplay

./cdromplay


You can see what I said before.

Do it in your real applications
As you know, we did some rubbish things before. There is no need to do so. But this is useful in some applications like CDburner - It will automatically eject tray after writing a CD ROM or you can control convineiently in a CD ROM player. We can use python to do a GUI application.

# File: cdromplay.py

import os
from Tkinter import *

class App:

def __init__(self, master):

frame = Frame(master)
frame.pack()
self.button = Button(frame, text="Quit", command=frame.quit)
self.button.pack(side=LEFT)

self.hi_there = Button(frame, text="Eject", command=self.say_hi)
self.hi_there.pack(side=LEFT)

def say_hi(self):
os.system("eject cdrom1 -T")
print "boss, cdrom activated"

root = Tk()

app = App(root)

root.mainloop()

As you can see, the above program is the altered version of "Hello World!" program of one famous python tutorial. Don't get upset or confused by the defnition names. The confusion in program code will not affect the real program.Copy and save it or download it from here. You require python to do this. 'cd' to the appropriate directory and run,

$python cdromplay.py


Now you will see a simple widget with a button.


Press button and observe what's happen.



Download cdromplay for python
Download cdromplay bashscript

Watch the video how cdrom is ejected:

Good Luck!