My Life As A Blog

Batteries Included

leave a comment »

Sometimes you’ll hear the Python standard library referred to as “batteries included” – a little more info hereIronPython can also use these included batteries.  As an example, today I needed to list the files in a folder.  So, a simple Python script seemed like a good way of doing that (I’m sure there are better and more ingenious ways.)  Here it is:

import os
import os.path
import sys
from optparse import OptionParser

def list_files(path, indent=0):
    for filename in sorted(os.listdir(path)):
        print " " * indent + filename
        full_path = os.path.join(path, filename)
        if (options.recursive) and (os.path.isdir(full_path)):
            list_files(full_path, indent + 2)
parser = OptionParser()
parser.add_option("-d", "--directory",
                  action="store", type="string", dest="path",
                  help="The directory to list.")
parser.add_option("-r", "--recursive",
                  action="store_true", default=False,
                  help="Whether to list subdirectories.")
parser.add_option("-f", "--output_file",
                  action="store", type="string", dest="output_file",
                  help="Directory contents will be listed to this file if specified.")

(options, args) = parser.parse_args()

if (options.path):
    path = options.path
    path = sys.path[0]

out = sys.stdout
if (options.output_file):
    output_file = open(options.output_file, 'w')
    sys.stdout = output_file


if (options.output_file):
    sys.stdout = out

As you can see, the script takes advantage of optparse to process the command line arguments, sys (to get the current folder and to get access to and redirect the output of the script), os (to list the contents of a folder) and os.path (to test if a given path is a folder.)  And, being IronPython, you also get a second set of batteries in the form of the .NET framework.


Written by remark

March 23, 2010 at 3:00 pm

Posted in .NET, Python

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: