Monday, August 11, 2008

Pylint On WingIDE Check on Save!

Now lets face it, for a data typeless language like python, its easy to get errors that other languages IDE would have picked up easily. For example, if you were to point "ooo = hellu()" and hellu() is actually a typo, it should have been "hello()". You wont get any error on the IDE until you run it.

This becomes pretty irritating when u have a number of these erorrs occuring when you are running your applications and you wished such flimsy bugs would have been picked by the IDE before you ever ran it.

Solution : Use Pylint.
Install it and goto "tools"->pylint and you will see a window on the right handside with "pylint" as the tab caption. (pls refer to other documentation on where to get and install pylint)

And what you need now is to have Pylint autocheck everytime u save a module so that all modules gets pre-checked and those irritating typos i mentioned earlier and other bugs will get caught.

Here is what you do, open up "editor-extensions.py" found in ur WingIDE installed directory under "scripts" (make a backup of this file first to somewhere else). Add the following lines at the end :-


def _connect_to_savepoint(doc):


def _on_savepoint(val):

if val == 0 :
return

# Get editor and do action
ed = wingapi.gApplication.GetActiveDocument()
if ed == None :
return

wingapi.gApplication.ExecuteCommand('pylint-execute')

connect_id = doc.Connect('save-point', _on_savepoint)


def _savepointinit():
wingapi.gApplication.Connect('document-open', _connect_to_savepoint)
for doc in wingapi.gApplication.GetOpenDocuments():
_connect_to_savepoint(doc)

_savepointinit()



And there you have it! Pylint total integration. Notice that if you open new modules and save it sometimes u get the "tried to execute an unavailable command .internal.gui.save". Just ignore this, the autosave in Pylint makes the IDE notice that you dont need to save the file again.

Thursday, August 7, 2008

Python : Working Directory Woes

Python has unittest that allows you to have a framework for testing your modules.
There is also nosetests. If you are using Wing IDE, there is a built in Test panel.
All is beautiful.

The problem is, if your project uses calls to "locate directory of where your script ran" you're in for a ride. Unlike windows api where u have a definite api to get this, the various ways in python to get the value resides in os.sys.path[0], sys.argv[0] and os.getcwd().

ALL the values you have seen will not get you the values you want, in unix when its run by using python or using the crond or when you run it from another script located elsewhere or in windows when you run it with "unittest, nosetests and even the Wing's Test panel" these values are going to give you a different result.

And then there is the py2exe ....which will give you yet another surprise as the path return is "\dist\library.zip"

Solution :

Temporarily put some guards for tests enviroment and use the following :-

def GetCurrentWorkingDir () :

if "Wing" in sys.argv[0] : return os.sys.path[0] + os.sep
if "nosetests" in sys.argv[0] : return os.sys.path[0] + os.sep

return os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + os.sep

Thursday, July 31, 2008

Py2exe and email.generator, email.blah blah errors

Create this file :-

import email
msg = email.MIMEText.MIMEText("dsafdafdasfA")
print "ok"

Create setup.py like below :

from distutils.core import setup
import py2exe
setup(console=['testmime.py'])


Run python setup.py py2exe and you will get errors

The following modules appear to be missing['email.Generator', 'email.Iterators', 'email.Utils']

And your program will bombed out with errors like ""Import error : No module name text"


To solve this i just added " print self.__name__" under __init__.py of \email package.
And it seems the LazyImporter is confusing py2exe.

Solution ?

import email
import email.mime.text
import email.iterators
import email.generator
import email.utils

Thursday, July 10, 2008

Python : POP3 SSL Gmail Proxy

There was a friend of mine who went to Macau and his company uses Gmail for hosting corporate emails. He has a local mailserver that would want to download from this gmail and it doesnt support POP3 over SSL (port 995).

So once again Python comes to the rescue, 2 hours later, its done. A generic POP3SSL proxy that will allow any mailserver/client to collect mails from gmail via POP3SSL.

Just run : pop3ssl.exe host port (ur local ip and port that u want to use as proxy)
Example : pop3ssl 10.8.0.1 110 (or if ur mailserver is in the same machine, use another port)

Download it here : pop3ssl.zip

Note although its free for use, pls leave a comment here on how this program helped you.

Wednesday, July 9, 2008

Pythonist Rants

Its interesting to see how Pythonist does some stuffs and then suddenly you find that doing that in some other language wasn't a bad idea either ....and then...suddenly (again) it dawns on you that many things could be done in Python that is IMPOSSIBLE to duplicate exactly .

Lets say you have a vector in C++ that you need to remove an item if it fits a certain scenario.

The layman's way is to do the following in C++ (not using algorightm stl ;-))

vector::iterator ptr;
for (ptr = abc.begin(); ptr != abc.end(); ptr++)
{
if (*ptr == "red")
{
abc.erase(ptr)
if (ptr == abc.end()) break;
ptr--
}
}


This is one of the way Pythonist does it :-


for x in abc[:]: # this means makes a copy of abc
if x == "red" :
acb.remove(x)

Yup, coming from C++, one's mentality one would wonder why we didnt use that similar method in Python in C++. However, this wouldn't work in C++ without futher modifications, this is because the "erase" is not taking a value but rather the iterator which means if you do this on the original vector but you passed in the iterator instance from the copy, it wouldn't work.


Then there is the story of smtpd.py. Its basically a smtp proxy/server skeleton that supports the basic commands. And how does one go and implement the "MAIL FROM", "RCPT TO", "DATA" method? The normal thinking would be to do a method/function for each of these commands and then there is the switch or if-else statement working on a read buffer.

How did smtpd.py do it?

method = getattr(self, 'smtp_' + command, None)
if not method:
self.push('502 Error: command "%s" not implemented' % command)
return
method(arg)

Introspection! It basically appends the command read and massaged from the buffer and append to the "smtp_" and invoke the method ....

Tuesday, July 8, 2008

Python fun project : MSN CHAT bot

I downloaded MSN-lib 3.6 from sourceforge and soon the naughty idea of linking this with Eliza
the therapist (joe, jeff , jez version of Eliza in python) cropped up almost instantly in my head.
So using a skeleton code of using MSN-lib i picked up from some forum, i did 1+ 1 = 2.

To make it realisic, i provide the "first msg" and the victim input before the bot takes full auto drive.

(All credits due to the original author and contributor to msnlib, eliza and related sources)

I must say i had a great time laughing over the chat logs as my friends and peers communicated with my chatbot. I made the program to log to some hardcoded directory of c:\msnbot since some sample codes is logging to some unix paths.

Well, if u need a break and a laugh, here is the chatbot and continue reading to find out how to configure it :-

Open the file : marbot.py, edit the values below and enter ur hotmail login and password.

m.email = "xxxx"
m.pwd = "xxxx"

Also change the name and nick to ur own :-

m.change_nick("-M- The future")

Ok, done now you are ready to go :-

python marbot.py

or just :

marbot.py

After running for a while it will ask 2 lines of input , the first line is the email id of the "victim" you intend to start a conversation with, the 2nd line is the first message you want to send to this person.

From then on, just watch and laugh as your friend communicate with Eliza. The logs are found in c:\msnbot (create this directory or unzip the files below to this directory)

Download the fun bot here

Monday, June 23, 2008

Visual C++ BrainBench Certification

I boldly went and took the Visual C++ BrainBench Certification without preparing myself in any refreshment task. I am very much caught in a surprise as i notice that the Visual C++ BrainBench actually means Windows programming in C++ , that includes OLE/COM, WndProc from scratch, device context and loads of other stuffs which frankly i have not been coding these natively but took the easy IDE way out.

It was a good test i must admit, it reveals to me how much i have taken for granted the advance tools and how much less i remembered of these subjects.

Here are the results anyway ( :-( scored within 3.x ...my python was 3.3, i was expecting a 4.x for a familiar language): BrainBench Visual C++ supervised :

Results for xxxxx

Test Takers Email: xxxxx

Date Taken: 23-Jun-2008
Test Event ID: ZC11178-CKQSJHX6

Overall Score: 3.56
Weights: 100% Visual C++
Elapsed time: 53 min 9 sec
Visual C++
Score 3.56
Percentile : Scored higher than 85% of previous examinees

Proficiency Level:
Advanced (Master)

Demonstrates a clear understanding of many advanced concepts within this topic. Appears capable of mentoring others on most projects in this area.

Strong Areas
General C++ Language
MFC
OLE/COM
General Windows Programming

Weak Areas
None noted