#!/usr/bin/python __doc__=""" make_program_info.py - Create 'program_YYYYSNNN.html' & 'sidebar.html' files from 'program_YYYSNNN.txt' files for HTML page. It is to be run in the current directory where program information files are. -v - verbose -h --help - shows this help Example: % cd /idas1/2021A/program_info && make_program_info.py """ import getopt import os import re import sys def usage(): print (__doc__) def find_program_txt_files( dir, sort = True, only_base = True, prog_re = r'program_(19|20)[0-9]{2}[AB][0-9]{3}.txt' ): """ Returns a list of base names of program ID directories. Arguments: dir : directory to search (non-recursive). sort : flag to return a sorted list. only_base: flag to return only base names, not complete paths. prog_re : regex to match against directory base name. """ out = list() for basename in os.listdir( dir ): path = os.path.join( dir, basename ) if re.match( prog_re, basename ): out.append( path if not only_base else basename ) if sort: out.sort() return out def write_program_html( program_html, program_txt ): """ Creates the html file for program_YYYYSNNN.html Arguments: program_html: write the html code to this filename. program_txt : name of the text file, ie: program_2016A001.txt """ html = """
""".format( program_txt ) with open( program_html, 'w') as fo: fo.write( html ) return def write_sidebar_html( filename, semester, program_list ): """ Creates the sidebar.html file for program_YYYYSNNN.html Arguments: filename: name of output file semester: semester string, ie "2016B" program_list: all the program_YYYYSNNN.txt filenames as a list """ with open( filename, 'w') as fo: # beginning of file html = \ """ """ fo.write( html ) return def main( argv ): debug = True try: opts, args = getopt.getopt(argv, "h", ["help", "debug=" ]) except getopt.GetoptError: usage() sys.exit(-1) try: for opt, arg in opts: # --help automatically prints doc string if opt in [ "-h", "--help" ]: #usage() sys.exit(0) elif opt == '--debug': debug = True if arg.lower() in ['on', 'true', '1', 'yes'] else False except: usage() sys.exit(-1) # Assume current working dir program_list = find_program_txt_files( "./" ) if debug: print( 'program_list: ') print( program_list ) # Extract the semester (YYYYS) from 1st element semester = re.search( 'program_(.+?)[0-9]{3}.txt', program_list[0]).group(1) if debug: print(" semester is (%s)" %(semester)); # Write a program_YYYYSNNN.html for each .txt file: for program_txt in program_list: # program_YYYYSNNN.html program_html = os.path.splitext( program_txt )[0] + '.html' print( " ", program_txt, " ...") write_program_html ( program_html, program_txt ) # write the sidebar.html file each .txt file: write_sidebar_html ( 'sidebar.html', semester, program_list ) sys.exit( main( sys.argv[1:] ) )