which python?

I came across a strange issue today. I have written a script that adds acronym tags to a post created in ecto, and another that adds the currently playing iTunes track, as nice links to iTMS. However, the problem that arose is that the script wouldn’t run. I had the shebang line, and everything, but no joy. Then I noticed that I have upgraded my python installation to 2.5, but for some reason the /usr/bin/python was still pointed at 2.3 - but my interpreter run from the bash shell, or from Komodo was 2.5. This itself wouldn’t be too much of an issue, except I was using appscript, and I had only installed appscript into the 2.5 Python installation library. So, it was failing (way too silently, for my liking), and I couldn’t tell why. All fixed now, though.

Fly Me Away • Supernature • Goldfrapp

appscript: Is application running?

This is the best way I can find to test if an application is running under appscript:

1
2
3
4
    try:
        app('System Events').processes['AppName']()
    except:
        print 'Application AppName is not running'

I think it’s kinda neat. I’d like to know of a better method, but I looked pretty hard!

Burn Down The Mission (Live) • Elton John • Live In Australia ★

wxPython

Maybe I’m just being crazy, but I’m not really finding wxPython particularly pythonic. For instance, I’m trying to make a fairly simple application that has a SplitterWindow, and I seem to have to do a whole lot of sub-classing to actually get it to work. Feels more like Java than Python. Which I’m really not keen on doing.

Notice • Gomez • Chillout Sessions 9

Getting Finder Comments in different languages

bash: mdls filename | grep FinderComment AppleScript: tell application "Finder"     comment of file end tell python: #!/usr/bin/pythonw from appscript import * path = '/Users/NAME/your/path/here' comment = app('Finder').items[path.replace('/', ':')].comment.get()

Komodo Macros

I’ve been working on a few little macros for Komodo. I’m planning to build a more cohesive set as I use the editor more.

Export HTML Tools.

The first is Copy As HTML Snippet. This gets an HTML representation of the current document and it’s syntax styling, and stores this in the Clipboard. There are two related tools: Export As HTML, and Export Selection as HTML. They save either the whole file, or the current selection. They create a new file, rather than store the data in the Clipboard. Each to her own. The code for each: (recursion: uses the macro to get the code of the macro…)

Copy As HTML Snippet.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from komodo import components, document  
from xpcom.server import UnwrapObject  
import re  
  
# Get the current buffer, and an html representation.  
buf = UnwrapObject(document.ciBuf)  
html = buf.to_html(False,False,None,True,True)  
# Remove some debugging code left by the developers.  
html = html.replace('onmouseover="show_class(event.target);"','')  
html = html.replace("'","'")  
html = re.sub('SCE_P_.*? ','',html)  
  
# Put it into the clipboard,  
ch = components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(components.interfaces.nsIClipboardHelper)  
ch.copyString(html)

Export As HTML

1
2
3
import komodo  
komodo.view.setFocus()  
komodo.doCommand("cmd_exportHTML")

Export Selection As HTML

1
2
3
import komodo  
komodo.view.setFocus()  
komodo.doCommand("cmd_exportHTMLSelection")

You can get a Project (mutliple part packages are broken on export for me at the moment) with all three macros from: HTML Export Tools.

Java Development Tools

This will eventually, I hope, become a more useful set of tools, perhaps being replaced by better interaction with, for example, Komodo’s native debugger. At the moment, debugging requires knowledge of the specific debugging commands. However, I am confident I can use the inbuilt Breakpoint structure to create breakpoints easily, and step through code.

Build & Execute

This macro calls a Command, at the moment, after saving the file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import komodo  
komodo.view.setFocus()  
komodo.doCommand('cmd_save')  
try:  
    komodo.findPart('command', 'Java Build & Execute', '*').invoke()  
except:  
    from xpcom import components  
    wwatch = components.classes["@mozilla.org/embedcomp/window-watcher;1"].getService(components.interfaces.nsIWindowWatcher)  
    prompt = wwatch.getNewPrompter(wwatch.activeWindow)  
    prompt.alert("Execution Error", "Unable to find 'Java Build & Execute'")  

Java Build & Execute

This is a Command, with the following in the Command: section if test “%F” -nt “%b.class”; then { javac “%F” ; if test “$?” == “0”; then java -classpath . “%b”; fi; } else java -classpath . “%b”; fi This should all be on the same line. In the Start in: box, insert %D

Java Build & Debug

Basically the same as the above, but with java replaced by jdb: if test “%F” -nt “%b.class”; then { javac “%F” ; if test “$?” == “0”; then jdb -classpath . “%b”; fi; } else jdb -classpath . “%b”; fi Start in: must be %D The project containing all of these can be found at Java Tools.

Python Tools

My python tools are a bit simple at this stage - after all, there’s already a fair bit of stuff in there to work with python! I do have a couple of bits that are useful. The Run Command… dialog is okay, but I always forget to save the document before running it, so I have two pairs of tools, one to Save and Run the file, and the other to Save and Run the file interactively. They are basically the same, with the difference of one command line switch, and the name of the command in the macro.

Save and Run Current Script

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import komodo  
komodo.view.setFocus()  
komodo.doCommand('cmd_save')  
try:  
    komodo.findPart('command', 'Run Current Python File', '*').invoke()  
except:  
    from xpcom import components  
    wwatch = components.classes["@mozilla.org/embedcomp/window-watcher;1"].getService(components.interfaces.nsIWindowWatcher)  
    prompt = wwatch.getNewPrompter(wwatch.activeWindow)  
    prompt.alert("Execution Error", "Unable to find 'Run Current Python File'")  

I’ve put a nice icon on it, which you can get by right-clicking on the following image, and downloading it.

Run Current Python File

This is a fairly simple one, there’s really only one trick. python -u “%F” And %D in Start in:, as before. The -u tells the interpreter not to buffer input and output.

Save and Run Interactively/Run Current Python File Interactively

Just add the word Interactively in the two places in the macro, and add -i in just before the -u in the command. Simple!

Execute Selection

Another simple one, this is just a python -u command that has the Pass selection as input box checked.

Execute All

A simple macro that selects all before running the above command. I may try to improve it so it re-selects the initial selection after. Maybe. I just used the macro builder to create this one. Cmd-A, then click on the Execute Selection tool. As before, get all of them from Python Tools.

The Closest Thing To Crazy • Katie Melua • Call Off The Search ★★★★★

Komodo IDE Python Interactive Shell

The python interactive shell on Komodo is pretty cool. I’d like it to be a bit more responsive, but I can’t really put my finger on what’s going on. I did notice, with python 2.5 that it pops up this traceback on a Ctrl-D:

    Traceback (most recent call last):
      File "/Applications/Komodo IDE.app/Contents/SharedSupport/dbgp/bin/pydbgp", line 270, in <module>
        sys.exit( main(sys.argv) )
      File "/Applications/Komodo IDE.app/Contents/SharedSupport/dbgp/bin/pydbgp", line 264, in main
        client.runInteractive()
      File "/Applications/Komodo IDE.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 1893, in runInteractive
        self.cmdloop()
      File "/Applications/Komodo IDE.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 2025, in cmdloop
        self.onecmd(data)
      File "/Applications/Komodo IDE.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 2145, in onecmd
        self.socket.send_response(str(ex))
      File "/Applications/Komodo IDE.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 1745, in send_response
        self._socket.send('%d\0%s\0' % (l, response))
    AttributeError: 'NoneType' object has no attribute 'send'

Eve Online written in Python

Apparently, Eve Online is written in Stackless Python.

Which should, in theory, make it easier to port to other platforms.

Perhaps.

Powered by ScribeFire.

Info Tech Studies Projects

I’m teaching Stage 2 Information Technology Studies this year (it’s turning out to be a fair bit of work, but I’m quite enjoying it), and I have to come up with some project topics. The students have to do two projects, one on each of the Option Topics we will be studying. At this stage, I’m planning on Application Programming (using python, and some form of GUI), and Website Programming (HTML+JavaScript). What I do need to do is think of some suitable project topics. Something that is challenging enough for Year 12, but not too difficult. I’ve got some ideas for Websites, as there is a bit more scope to do something cool. It’s a bit easier to implement cool stuff with a more limited level of skill in HTML than it is in an application program. I also have to write some skills tasks, that assess each of these topics. I’ve got some good ideas here for the application programming one (give them the GUI code, and get them to make the backend, and for the other, give them some working application code, but as a series of functions, and get them to combine the functions into a full application). I’d love to be in a situation where I could teach ObjC, since I do have a Mac computer room at school, but since I don’t know it that well myself, that might be a future task. I seriously wish anygui had taken off. But, even late in the game then, I wasn’t really keen on how the backend interface was turning out. I came across Dabo yesterday, and that looks cool, though.

Python GUI Alternatives

I’m teaching Information Technology Studies to final year High School students this year, and one of the topics I am teaching is Application Programming. I’d prefer to stay away from Visual Basic if possible, and I’m re-investigating currently available GUI construction methods for python. Back in the 90s, I was involved in the anygui project, which was a lofty plan to create a GUI equivalent to the anydbm interface that python uses for accessing the most easily available database backend. I’m not talking SQL or Access, but simpler database stores like bsddbm and the like. This project never reached fruition, although we got lots of code sorted out. One of the alternatives that I find really exciting seems to be an intellectual successor to this project: ClaroGraphics. This goes even further, having the plan to be a GUI library for C, C++, python, ruby, anything. I’m not sure that it will be feature complete by the time I get to it (second term), but it most certainly looks exciting. It may be that I’m better of sticking with EasyGUI, which is a non-event driven GUI system, which basically allows for dialogs and interaction using a GUI, rather than having to use text. This could be a goer, I’ll have to check that out too. An alternative might be to use Eclipse, with Jython. That allows for python syntax, but cross-platform GUI Java style. I think. More research needed.

Welcome back, python

It’s been too long since I last coded in python. I’ve been doing a fair bit of AppleScript, and JavaScript over recent months, but tonight I had cause to do some scripting in python. And, how I’ve missed it. I still keep wanting to write if (something) then, but I’m getting over it. I’ve been doing some stuff to organise digital photos, as indicated in the previous post. What I’ve come up with so far is some code that grabs the EXIF data from the file, and if it’s a photo (and larger than 640, to remove thumbnails from the process), move/copy/link it to a particular location. This location is $base_dir/year/month/day/, where $base_dir is a definable constant, and year/month/day is grepped from the EXIF data. I’ve come up with two simple methods of getting the EXIF data - one is to use the EXIF.py module (not installed by default), the other uses jhead. The jhead one is much faster, but I wonder whether I can hand-code one that is even faster, since I only need three bits of data (date, xSize and ySize). [Some time passes…] A grep is marginally faster, but is only easy to do when you know the structure of the data you are looking for. A Date/Time is easy:

1
    grep '[12][0-9][0-9][0-9]:[01][0-9]:[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]' -m1 -o -a filename.JPG

But getting the same for a resolution (which could just be any value that is a multiple of 8, or even any other number if the image had been edited!), is a bit tricky. Regardless, jhead is much, much faster than EXIF.py, by several orders of magnitude. So I’ll use that. Anyway, the cool bits of my code are:

1
2
3
4
5
6
7
8
9
    date_string = os.popen('jhead ' + filename + ' | grep Date/Time').read().split(' : ')[1].strip()
    
    resolution = os.popen('jhead ' + filename + ' | grep Resolution').read().split(' : ')[1].strip().split(' x ')
    
    if resolution[0] < 640 and resolution[1] < 640: 
        return None # Low-res, must be a thumbnail.
    
    date_dir = os.path.join(base_dir, date_string.split(' ')[0].replace(':','/'))
    

I’m fairly happy with these bits of code, and of course there are more things being added. I do have it working that it grabs the data, and creates links in the chosen directory. I’ve decided to use links until I’ve finished getting all of the album data from iPhoto, since then I don’t have to worry about disk space (hard links don’t take up any room, they are just another reference to the file). Jaq wanted to know if there was a UI for my system - I think there will be. Initially, it will just be using the Finder (and perhaps some Folder Action Scripts to move the files to the right locations), and Spotlight to index the files, but I may move to a proper UI. I think I’ll still use Spotlight as the data store - that way it doesn’t rely on an external database, and if the data is fixed, it updates in my system automatically. Unlike iTunes. This is really heading back to the way it could be done in BeOS. I could have just had this system, and a series of Queries, and it would have all been beer and skittles. The next step will be to look at Albums. At this stage I’m thinking of using hard links for albums, but the thing that worries me about that is the Macintosh’s habit of not rewriting to a file, but saving a new copy, and then overwriting that. Perhaps soft links will be better for Albums. Again, that will rely on the OS doing the maintenance, not my application. Of course, the problem might be with Spotlight not really indexing files that well. I’ve run mdimport, and only one file seems to really be appearing. The others appear as ‘ghost’ files, that AFAIK are aliases. Or so it appears to the system.

Barber’s Adagio For Strings • William Orbit • Open Space ★★★★