#!/usr/bin/python ''' A script that creates index.html indexes for a folder. ''' import os,sys import urllib INDEXFILE='index.html' def setup(): ''' Setup the command line options ''' from argparse import ArgumentParser parser=ArgumentParser() parser.add_argument("-f",action="store_true",dest="overwrite",default=False, help="Overwrite existing "+INDEXFILE) parser.add_argument("-H",action="store_true",dest="hidden",default=False, help="Show hidden files") parser.add_argument("-t",type=str,dest="title",default=None, help="Name for the title (Default: Folder name)") parser.add_argument("-p",action="store_false",dest="parent",default=True, help="Do no print .. link for parent folder.") parser.add_argument("startpath",type=str,action="store",default=os.path.abspath('.'),nargs='?', help="Root path of the index") options=parser.parse_args() options.startpath=os.path.abspath(options.startpath) if options.title==None: options.title=os.path.basename(options.startpath) return options def generate_index(opts): for path,dirs,files in os.walk(opts.startpath): if INDEXFILE in files: if not opts.overwrite: print(INDEXFILE+" exists") sys.exit(1) files = [ f for f in files if f != INDEXFILE] if not opts.hidden: files = [ f for f in files if not f.startswith(".")] dirs = [ d for d in dirs if not d.startswith(".")] f=open(os.path.join(path,INDEXFILE),'wt') dirs.sort() files.sort() f.write(get_header(opts.title)) if opts.parent: f.write(get_pathlink('..')) for pa in dirs: f.write(get_pathlink(pa)) for fi in files: f.write(get_filelink(path,fi)) f.write(get_footer()) f.close() return def get_filelink(path,fname): fsize=os.path.getsize(os.path.join(path,fname)) fsstr=sizeof(fsize) return ''+fname+''+fsstr+'\n' def get_pathlink(path): return ''+path+'\n' def get_header(title): header=''' Index of '''+title+'''

Index of '''+title+'''

''' return header def get_footer(): footer='''
NameSize
''' return footer def sizeof(num): for x in ['bytes','KB','MB','GB','TB']: if num < 1024.0: if x=='bytes': return "%d %s" % (num, x) return "%3.1f %s" % (num, x) num /= 1024.0 opts=setup() generate_index(opts)