Gabriel's Musings

March 16, 2009

Python Commandlets Redux

Filed under: Computers, Python — Tags: — ggellner @ 9:47 pm

Reading the awesome python blog word aligned I was directed to the cool python code snippet at voidspace that creates a simple class for making unix shell like pipes for functions in python. Thinking this was cool, I ported over some of the Ironpython specific features to be CPython compatible, and used the classes as decorators as I think this makes the code more direct.

The compatibility parts where to replace ‘System.DateTime.Parse’ to the dateutil function ‘parse’, which returns a datetime object and not a float like the IronPython call. So I then updated the Path object to store datetime objects for ‘mtime’ and ‘ctime’, which I think is nicer anyway. The Full code is:


import os
from dateutil.parser import parse
from datetime import datetime
from cmdlet import Cmdlet, Action

class Path(object):
    def __init__(self, path, entry):
        self.dir = path
        self.name = entry
        self.path = os.path.join(path, entry)
        self.mtime = datetime.fromtimestamp(os.path.getmtime(self.path))
        self.ctime = datetime.fromtimestamp(os.path.getctime(self.path))

    def __repr__(self):
        start = 'File:'
        if os.path.isdir(self.path):
            start = 'Dir:'
            ctime = self.ctime
            mtime = self.mtime
            return "%s %s :ctime: %s :mtime: %s" % (start, self.path, ctime, mtime)

@Cmdlet
def listdir(path):
    def listdir():
        return [Path(path, member) for member in os.listdir(path)]
    return listdir

@Cmdlet
def notolderthan(date):
    datetime = parse(date)
    def notolderthan(member):
        if member.mtime >= datetime:
            return member
        returnĀ  ignored
    return notolderthan

@Action
def prettyprint(val):
    print val

if __name__ == '__main__':
    listdir('.') >> notolderthan('2/3/08') >> prettyprint

The module cmdlet just contains the Cmdlet and Action class definitions as found in the orginal web posting.

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Shocking Blue Green. Blog at WordPress.com

Follow

Get every new post delivered to your Inbox.