#!/usr/bin/env python def usage(): print ''' lyinclude.py flattens lilypond files one level. Usage: lyinclude.py infile > outfile lyinclude.py dumps infile, expanding each \include "subfile" to the content of subfile. (c)2003 David Raleigh Arnold under GNU Thanks to Patrick Atamaniuk for his revisions. ''' sys.exit(1) import string, sys, os '''If there is infile, do it''' if sys.argv[1:]: if os.path.isfile(sys.argv[1]): infile = open(sys.argv[1]) else: print "File " + sys.argv[1] + " does not exist in this directory." usage() else: usage() try: ''' Get standard input. ''' for inline in infile.readlines(): '''Clean line. ''' inputline = string.rstrip(inline) ''' Finds position of "\include" on line. ''' includepos = string.find(inputline, "\\include") ''' If no "\include", (else) prints line. ''' if includepos >= 0: ''' Finds comment '%' on line. ''' commentpos = string.find(inputline, "%") ''' If not comment, else print line. ''' if commentpos < 0: '''Slice and dice the line...''' '''Splits line at the \include, also removes the separator. ''' half = string.split(inputline, "\\include") ''' The first half of the split line: ''' leadinghalf = string.rstrip(half[0]) '''The first word in the other half is the name of the file to be expanded. Using double quote to find filename instead of space. Strip space from left. ''' otherhalf = string.strip(half[1]) '''Using double quote to split again, so rehalves[0] is empty. ''' rehalves = string.split(otherhalf, '"', 2) includefile = rehalves[1] tail = string.lstrip(rehalves[2]) '''Finds out whether included file exists. ''' value = os.path.isfile(includefile) if value > 0: '''Prints the leading half of the line _if_ it contains data. ''' if not string.strip(leadinghalf)=="": print leadinghalf ''' Scan the file and print its contents. ''' for line in open(includefile, 'r').readlines(): print line[:-1] ''' Print the part of the line after the \include "xxx.ly", if data. ''' if not string.strip(tail)=="": print tail else: print inputline, print '%' else: print inputline else: print inputline except: usage() '''Reachable if Usage commented out: ''' print "python errors:" print sys.exc_type, sys.exc_value