Apple PyObjC tutorial (Cocoa programming with Python)

February 12, 2006

This is Apple’s tutorial about programming Cocoa with Python. It’s an easy one, but read it if you want to start programming Cocoa with Python. It is quite well done.

Here PyObjC website.


MacOS X Intel & Rosetta: application compatibility

February 10, 2006

This site keeps an updated list of software that works with Rosetta and how they work. For example some applications do work, but with serious performance issues. If you have to use them professionaly (or often) you should consider not to go with Intel Macs and stay with old Macs.

With some other applications however Intel performances are quite impressive.


Opera 9 (preview)

February 7, 2006

La prima cosa che salta all’occhio è la nuova interfaccia. Più browser e meno “pacchetto integrato”. Di default ci viene mostrato solo il minimo indispensabile come si vede nello screen

Toolbar Opera

Le classiche toolbar sono comunque tutte accessibili attraverso il solito Menu.

La prima cosa che faremo sarà caricare una pagina. Qui rimarremo sorpresi. La velocità è impressionante (sicuramente la velocità percepita). Anche il resto del programma rimane decisamente reattivo.

Alcuni binding sono cambiati (per esempio adesso per aprire un nuovo tab possiamo usare Mela-T/Ctrl-T come su Firefox e Safari, mentre prima, se la memoria non mi inganna, era Mela-Option-N, con eventualmente sostituito Mela da Ctrl se sotto X11 o Windows).

I bookmark sono stati importati in un batter d’occhio. Bene. Per posta e altro non mi esprimo, non sono funzioni che uso, preferendo di gran lunga programmi apposta, come Apple Mail e NetNewswire — newsfeed –).

Il problema più grosso temo sia *esportare* i bookmark. Passare da un altro browser ad Opera è facile, non altrettanto facile il contrario, purtroppo. L’ultima volta lo feci attraverso un servizio web esterno (questo) . Tale sito fra le varie cose offre un convertitore di file di bookmarks da e per moltissimi programmi diversi.

AJAX pare funzionare bene (a parte un problemuccio su WordPress, qui, sulle immagini, ma cose “complesse” come per esempio l’editor di post WYSIWYG in javascript avanzato funziona decisamente bene).

Ribadisco… veloce, interessante. Vediamo Google cosa inventerà, perchè per adesso Opera 9 sembra una versione riveduta e corretta di Opera 8, ma non offre davvero quanto Firefox, ne è integrato come Safari.
Comunque da tenere sott’occhio senza dubbio.


Abiword on MacOS X

February 7, 2006

Funny… this are a couple of screenshots I got running Abiword straight from the .dmg, without installing it.
I was just to file a bugl (that is to say 1- check if someone filed the same bug 2- if not, file), when I tried to run it from the desktop (or Application directory). In this case, no troubles of any sort.

The screenshots below do refer only to Abiword run from the dmg. Even if we can call this a bug, it’s harmless and you have to know it is there to find it.

You probably expected some more comments… maybe another time. What can I say is that at first sight it looks really good, a fast one.

abiword_funny2
abiword_funny1


List user defaults in MacOS X

February 5, 2006

The small script below uses PyObjC (it was born as a snippet in ipython to have a quick check to a pair of variables). Of course you can write the very same thing in ObjectiveC.

I strongly encourage to install PyObjC and ipython even if you do work with Cocoa and ObjectiveC, since you can use that to prototype your application and to test snippets of code.


#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import Foundation

ud = Foundation.NSUserDefaults.standardUserDefaults()
d = ud.dictionaryRepresentation()

for k in d:
    sys.stdout.write(k)
    sys.stdout.write(":\t")
    try:
        print d[k]
    except UnicodeEncodeError, e:
        print d[k].encode('utf-8')

    

To have more information on PyObjC (that is to say Cocoa bindings for Python), go here.

You can find ipythonhere. ipython in an improved interactive shell, with powerful introspection capabilities.
Since MacOS X Python by default comes with no support for readline, I advise to install the missing module for Python 2.3 (search google, I don’t remember right now where to find it) or better install this version of Python 2.4, complete with the patch (on the same page).
Of course you must set your path so that the “first” python is the new one (if you set PYTHON_ROOT and such, you must also fix them).

Remember when you “python setup.py install” a module (that is the typical command line to install a python package), it is installed for the python version called by default (find it out with which pyhon)


Execute class: $(command) in python

February 3, 2006

Although you can easily do with module subprocess what I do with the following class:

  • If you have Python 2.3 you may not have subprocess
  • This class is much simpler than subprocess: it does just one thing.
  • You may want to pipe two commands in a fancier way

I wrote this because I needed to use Python to do some system automation and I needed something that acted like Perl and bash `` (in bash 2 you are supposed to do $(command) instead of `command` but it’s syntactical sugar).

In my strive to be compatible with standard MacOS system (which du use 2.3 by default) I forgot it existed module subprocess. So I wrote this simple class.

Even if in production you may prefer to use subprocess you can consider this an example of streams in Python. This is a very simple example. If you want to really pipe two processes, use module subprocess. If you want to make streams in a C++ fashion you can take inspiration by this code, but you may want to do it line based (but this ain’t no problem, in fact we are using properties, so you can do whatever you want with them — an example later).

Stream acts like a Mixin (thanks Dialtone!). It defines __rshift__ and __lshift__ (that become >> and


class Stream(object):
    def __rshift__(self, rho):
        if isinstance(rho, Stream):
            rho.input = self.out
            return rho
        else:
            raise TypeError()

    def __lshift__(self, rho):
        if isinstance(rho, Stream):
            self.input = rho.out
            return self
        else: raise TypeError()
    

Remember: classes that subclass Stream must have an attribute named out and one named input. If you need something more complex, use properties to implicitly call functions every-time you access out or in. For example since I use lazy evaluation I do:


    input = property(fset=set_input, fget=get_input)
    out = property(fget=get_out)
    err = property(fget=get_err)

Now have a look at the whole code:


import os

class Stream(object):
    def __rshift__(self, rho):
        if isinstance(rho, Stream):
            rho.input = self.out
            return rho
        else:
            raise TypeError()

    def __lshift__(self, rho):
        if isinstance(rho, Stream):
            self.input = rho.out
            return self
        else: raise TypeError()

class Execute(Stream):
    def __init__(self, command, *kargs, **prefs):
        self._commandString = ' '.join((command,) + kargs)
        self.has_run = False

    def _lazy_run(self):
        if self.has_run: return
        self.has_run = True
        (self.sin, self.sout, self.serr) = os.popen3(self._commandString)
        self.sin.write(self.input)
        self.sin.close()
        self.out_list = list([line.strip() for line in self.sout])
        self.err_list = list([line.strip() for line in self.serr])

    def run(self):
        self._lazy_run()
        return self

    def _make_string(self, which):
        self._lazy_run()
        if hasattr(self, "%s_string" % which):
            return
        setattr(self, "%s_string" % which,
                    '\n'.join(getattr(self, "%s_list"% which)))

    def set_input(self, s):
        if hasattr(self, "input"):
            self.input_ = "%s%s" % (self.input, str(s))
        else:
            self.input_ = str(s)

    def get_input(self):
        try:
            return self.input_
        except AttributeError:
            return ""

    def get_out(self):
        self._make_string("out")
        return self.out_string

    def get_err(self):
        self._make_string("err")
        return self.err_string

    input = property(fset=set_input, fget=get_input)
    out = property(fget=get_out)
    err = property(fget=get_err)

    def __str__(self):
        return self.out

print Execute("cat Execute.py") >> Execute("wc -l")
print Execute("wc -l") << Execute("cat Execute.py") 

If you need to do different things, redefine (get|set)_(out|input|err).


Wonderful Terminal…

February 2, 2006

I just love it. Yeah… an old screen on my Mac.

http://ldopa.net/2006/01/14/glterminal/


Emacs bindings in Cocoa?

January 30, 2006
Key Meaning
ctrl-q Beeps. If pressed twice deletes selection.
ctrl-w Cuts text
ctrl-e Moves to end of line
ctrl-r Beeps??
ctrl-t Swaps near characters
ctrl-y Pastes text
ctrl-u Beeps??
ctrl-i Beeps??
ctrl-o Insert new line after current
ctrl-p Moves cursor to previous line
ctrl-a Moves to beginning of line
ctrl-s Beeps??
ctrl-d Deletes character on the right
ctrl-f Moves forward one character
ctrl-g Beeps??
ctrl-h Deletes character on the left
ctrl-j Beeps??
ctrl-k Cuts line from cursor to the end
ctrl-l Does nothing?
ctrl-z Beeps??
ctrl-x Beeps??
ctrl-c Beeps??
ctrl-v Moves half screen down
ctrl-b Moves backward one character
ctrl-n Moves cursor to next line
ctrl-m Beeps??

TextMate: the definitive editor?

January 29, 2006

Unfortunately it appears I’ve no time to talk about programming. It takes lot of time to think about something useful, to write examples and such. However, I promise I will doing it soon.

And yet I’m again talking about a text editor. In fact since most of my computer time is spent on an editor, this makes sense. It’s the most crucial application to me (and the one I spend most time to learn using its full power).

I already said I discovered TextMate. The more I study the more I’m amazed. In fact it did substitute Aquamacs even for latex editing. The new bundle is perfectly integrated with Texniscope and “Command-B” opens in TextMate the pdf document compiled from the document I’m editing. That makes environment such that TexShop almost useless to me.

Emacs is more powerful. But most of the times I’m not using that power. It’s my fault, of course. Still TextMate is always open on my Mac, and I started using it even for latex. That’s the main reason. If I have to do a very long latex editing session I still do prefer Aquamacs.

The Python mode is now wonderful. It lets me check my sources with pychecker or with pyflakes. It allows me to run them from inside TextMate, lets me run unit-tests with one command. And even more. Right at the moment it’s the best python programming environment I’ve ever met (a part from WingIDE).

The only thing I’m missing right now is a “prolog mode”. And probably I have to work on TextMate/Xcode integration (it has been done, but I haven’t done it yet). Oh, and I’m looking forward to see TextMate 2, that should have massive improvements on the “project management” side. And probably I’d like some more refined auto-completion with static languages. This could have somehow been added (TextMate can be extended and customized a lot, still in a really simple way), but I’ve not yet discovered if and how.

But the reason I wrote this is another. For years the “Text editors” with capital T have been Emacs and vim. BBEdit was a beautiful Mac editor, but first it is very web-oriented, second it is somehow less powerful in the way it deals with text.

On the windows platform I have not found really impressive text editors. There are a bunch that are powerful and easy to use. But in fact I installed vim (gvim) and I was happy with that. Most such editors were more concerned in “integrating” command line utilities (compilers, latex, interpreters) with the editor not to have the “programmer” opening the “DOS console” than pure text editing.

Newer editor for Linux (Kate for example) also paled in comparison with Emacs or vim. Now I’m wondering:

  1. Was I superficial? It is possible that no one did something that could be compared with vim or Emacs before TextMate? This seems really unlikely.
  2. Why haven’t I spotted such editors? They exist? Let me know. I’m talking about “pure text editors”, not about “IDEs”.

GeekTool CPU Script

January 28, 2006

If you don’t know what GeekTool is go here.
It is very likely you’ll find it useful. If you use Tiger, use this version that fixes a lot of issues.

GeekTool allows you to put a lot of interesting informations on the desktop. You can “print” logfiles on the desktop or you can put there pictures or, and that is what is interesting, put the output of a chosen command.
For example I put a random fortune on the desktop. It easier to do download GeekTool and do it than reading an explanation.

An interesting feature that is in the documentation (so it’s something you probably wouldn’t read) is that scripts/commands placed in “~/Library/Application Support/GeekTool Scripts” need not to be specified with full path. So we will put the script “cpuload.py” in that directory and we will refer to it with “cpuload.py”

And now the script:


    #!/usr/bin/python
    # -*- coding: utf-8 -*-

    import os

    class command(object):
        def __init__(self, c):
            self._command = c
            fi, foe = os.popen4(self._command)
            fi.close()
            self.out = list([line.strip() for line in foe])
            foe.close() 

    def cpu_load(string_list):
        # a bit functional... not pythonic at all
        return sum(map(lambda l: float(l.split()[2]),
            string_list), 0)

    def main():
        ulist = command("ps -ux").out[1:]
        slist = command("ps -aux").out[1:]
        print "System CPU: ", cpu_load(slist), "%"
        print "User CPU:   ", cpu_load(ulist), "%"

    if __name__ == "__main__":
        main()

Class “command” is a stripped down version of a class I’m writing for another project. I also think that any script you write should be executable.