Posts Tagged ‘python’

Enable vim code (Python) auto complete

Written on December 27th, 2007 by shakir
Categories: Information Insemination

Beginning version 7 of vim, it has this nice auto completion feature. It is by default however limited to words that has already been in the current workspace. To use it, simply press [ctrl] +n or [ctrl] + p key while in edit mode. For example:

We can however *teach* vim to autocomplete a whole bunch of other stuffs as well, by using something so called Dictionaries. With this idea we can have auto completion for Python, Ruby, PHP, Bash, and any other programming languages code.

For an example, let’s try to install Python dictionary, by downloading it from here:


http://www.vim.org/scripts/script.php?script_id=850

The next thing to do is to extract the downloaded file to the appropriate folder:

shakir@herugrim ~ $ mkdir ~/.vim
shakir@herugrim ~ $ tar xvzf pydiction-0.5.tar.gz -C ~/.vim

and add this lines to your ~/.vimrc (be sure to replace "/home/shakir" to your own home directory)

if has("autocmd")
    autocmd FileType python set complete+=k/home/shakir/.vim/pydiction-0.5/pydiction isk+=.,(
endif " has("autocmd"

and let’s see the result:

Browse around the Vim script page and your customized Vim could be just as good if not better than some IDEs.. :)

Interactive Python shell with IPython

Written on December 15th, 2007 by shakir
Categories: Information Insemination

One nice thing about Python as compared to some other scripting languages, is that it has a shell that enables us to test our Python script on the fly without needing to write a script file first

It’s nice and all that, but when you’re too used to IDEs which has features such as auto completion etcetera, you’ll feel like something is not right about the default python shell.

That changes when I come to IPython, one of the few other enhanced Python shell. The one feature I like most is the auto complete feature, which among other by using it I don’t need to remember module names, and at the same time would list and try Python modules that I’ve never heard of.

In Ubuntu, or debian in general, the package is called ipython, and to install it just;

shakir@herugrim ~ $ sudo apt-get install ipython

Can you spot the differences between this

shakir@herugrim ~ $ python
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import command
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named command
>>> import commands
>>> status, output = commands.getoutputstatus ('ls')
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'getoutputstatus'
>>> status, output = commands.getstatusoutput ('ls')
>>> print output
Desktop
Documents
Music
Photos
>>>
shakir@herugrim ~ $

and this?

shakir@herugrim ~ $ ipython
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
Type "copyright", "credits" or "license" for more information.

IPython 0.8.1 -- An enhanced Interactive Python.
?       -> Introduction to IPython's features.
%magic  -> Information about IPython's 'magic' % functions.
help    -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import command
---------------------------------------------------------------------------
           Traceback (most recent call last)

/home/shakir/ in ()

: No module named command

In [2]: import commands

In [3]: status, output = commands.
commands.__all__           commands.__hash__          commands.__setattr__
commands.__class__         commands.__init__          commands.__str__
commands.__delattr__       commands.__name__          commands.getoutput
commands.__dict__          commands.__new__           commands.getstatus
commands.__doc__           commands.__reduce__        commands.getstatusoutput
commands.__file__          commands.__reduce_ex__     commands.mk2arg
commands.__getattribute__  commands.__repr__          commands.mkarg

In [3]: status, output = commands.gets
commands.getstatus        commands.getstatusoutput

In [3]: status, output = commands.getstatusoutput('ls')

In [4]: print output
Desktop
Documents
Music
Photos

In [5]:
Do you really want to exit ([y]/n)? y
shakir@herugrim ~ $

I hope you can guess when did I press the [tab] key :)

“‘BoundMetaData’ is not defined” error in SQLAlchemy

Written on December 13th, 2007 by shakir
Categories: Information Insemination

I get this error when creating a BoundMetaData object in SQLAlchemy 0.3.10. The fix is to just use MetaData instead of  BoundMetaData. BoundMetaData is deprecated and replaced with MetaData

Example code:

from sqlalchemy import *

db = create_engine('sqlite:///test.db')
metadata = MetaData(db)

"""
  Continue with the rest of your Python code
"""

Books…

Written on November 26th, 2007 by shakir
Categories: Information Insemination, Nerd Public Journal?

I went to One Utama MPH to get myself the last available copy of the LPI Linux Certification In A Nutshell book, to not fail my LPI 20x exam, again :( Though I prefer Exam Cram series more for the purpose, this book seems to be the only option that I have, as other books doesn’t cover LPIC 2 exams. I’ve also bought the CSS book just to add to my Pocket Reference series of collection.

Though I’m not into it,  LPIC 1 Exam Cram 2 was also not available. I blame Ditesh for the shortage :)

I was also looking for Python Cookbook, and Django or Pylons books, but they were all not on the shelves. With this I pledge anyone who has these books to come forward and help me with that, haha.

# The LPI manual provided by the savannah project doesn’t really cover LPI syllabus, and so if you’re planning to pass your LPI exams, don’t just rely on them. Experience speaks :D

# There was only 7 Python books at One Uutama MPH by the time I was there. How sad.

“DeprecationWarning: SessionMiddleware is moving to beaker.middleware in 0.8″ error in (K)Ubuntu

Written on November 14th, 2007 by shakir
Categories: Information Insemination

I’ve been getting this error when running paster for my Pylons project:


shakir@herugrim ~/Misc/workspace $ paster serve –reload development.ini
Starting subprocess with file monitor
/var/lib/python-support/python2.5/pylons/wsgiapp.py:249: DeprecationWarning: SessionMiddleware is moving to beaker.middleware in 0.8
  app = SessionMiddleware(app, config.global_conf, **config.app_conf)
/var/lib/python-support/python2.5/pylons/wsgiapp.py:254: DeprecationWarning: CacheMiddleware is moving to beaker.middleware in 0.8
  app = CacheMiddleware(app, config.global_conf, **config.app_conf)
Starting server in PID 8550.
serving on 0.0.0.0:5000 view at http://127.0.0.1:5000

On my quest to solving it, I uninstall Pylons (its whole bunch of dependencies);

sudo apt-get remove python-pylons

and install it back again, but this time using easy_install;

sudo easy_install Pylons

Yeay, I’m now good to proceed. Happy coding to me :D

Prefix WhoIs in Python

Written on November 10th, 2007 by shakir
Categories: Information Insemination

Part of a project I’m into requires me to dig for some details on IP addresses. Normal whois query (default to whois.apnic.net) don’t give me the information that I really need for, and upon searching I came to the Prefix Whois Project. They have came up with whob, and from the website I get to know that I can even get part of whob‘s functionality by just to query for whois from their server. Let’s try with our favorite’s TMNut Screamyx DNS

 

shakir@herugrim ~ $ whois -h whois.pwhois.org 202.188.0.133
IP: 202.188.0.133
Origin-AS: 4788
Prefix: 202.188.0.0/19
AS-Path: 6079 4788
AS-Org-Name:
Org-Name: Asia Pacific Network Information Centre
Net-Name: APNIC-CIDR-BLK
Cache-Date: 1195082506
Latitude: 3.167000
Longitude: 101.700000
City: -
Region: -
Country: MALAYSIA

I’ve just started to learn, and like Python, and let’s see my Python example to extract the whois info;

import commands

def main():

    whoisServer = "whois.pwhois.org"
    IPAddr = "202.188.0.133"

    status, output = commands.getstatusoutput('whois -h ' + whoisServer + " " + IPAddr)

    result = {}

    for i in output.splitlines():
        stripped = i.split(':')
        result[stripped[0]] = stripped[1]

    print result

if __name__ == "__main__":
    main()