py2html.html
001| '''Python to HTML.
001|
001| Functions:
001| python_to_html (py_filename, html_filename, log)
001| python_to_html_file (*args) -- alternate that uses tokenize().
001| python_to_html_frag (*args) -- alternate that uses tokenize().
001|
001| parse_python (filename, fpath, log)
001| write_output_html (toks, filename, fpath, line_nbrs, log)
001| write_fragment_html (toks, filename, fpath, line_nbrs, log)
001| write_output_listing (toks, filename, fpath, lines, log)
001|
001| document_module (configuration, module_name)
001| document_module_list (configuration)
001|
001| Classes:
001| TextParser () -- Parser class
001|
001| '''
002|
003| from sys import path as syspath
004| from os import path, environ
005| from tokenize import tokenize, untokenize
006| from token import tok_name
007| from keyword import iskeyword
008| from xml.sax.saxutils import escape
009| from files import textfile
010| from webpage import WebPage, EOL
011|
012| CssFiles = ['/basic.css', '/pub/python/python.css']
013|
014|
015|
016|
017|
018|
019| Keywords = [
020| 'False' , 'None' , 'True' , 'and' , 'as' , 'assert',
021| 'async' , 'await' , 'break', 'class' , 'continue', 'def',
022| 'del' , 'elif' , 'else' , 'except', 'finally' , 'for',
023| 'from' , 'global' , 'if' , 'import', 'in' , 'is',
024| 'lambda', 'nonlocal', 'not' , 'or' , 'pass' , 'raise',
025| 'return', 'try' , 'while', 'with' , 'yield' , '__main__',
026| 'self' , '__init__',
027| ]
028|
029|
030| Functions = [
031| 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray',
032| 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'delattr', 'dict',
033| 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format',
034| 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
035| 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals',
036| 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open',
037| 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round',
038| 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
039| 'tuple', 'type', 'vars', 'zip', '__import__',
040| ]
041|
042|
043| Styles = {
044| 'name' : 'color:#000000;',
045| 'keyword' : 'color:#0000ff; font-weight:bold;',
046| 'function' : 'color:#9900ff; font-weight:bold;',
047| 'op' : 'color:#000099;',
048| 'string' : 'color:#009900;',
049| 'docstr' : 'color:#cc3300; ',
050| 'number' : 'color:#ff0000; font-weight:bold;',
051| 'comment' : 'color:#999999; font-style:italic;',
052| 'linenbr' : 'color:#cccccc;font-style:normal;font-weight:normal;',
053|
054| 'fstring_start' : 'color:#009966;',
055| 'fstring_middle' : 'color:#009900;',
056| 'fstring_end' : 'color:#009966;',
057| }
058|
059|
060| def write_output_html (toks, filename, fpath=None, line_nbrs=True, log=None):
061| '''Write HTML Output File.
061| args:
061| toks list of Python Tokens
061| filename filename of output file (None: fpath is an open file object)
061| fpath pathname of output file (None: filename is a full filename)
061| line_nbrs True or False (default=True)
061| log logger object (default=None)
061| '''
062| if log:
063| log.info('HTML: %s' % filename)
064|
065| html_div = '<div style="font-family:monospace;font-size:11px;line-height:1.3;">\n%s'
066| html_span = '<span class="%s">%s</span>'
067| html_br = '<br>\n%s'
068| def html_eol (htm, ln):
069| '''End of line + Line number for next.'''
070| if line_nbrs:
071| html_lnbr = '<span class="%s">%03d| </span>' % ('linenbr',ln)
072| return htm % (html_lnbr)
073| return htm % ''
074|
075| if filename:
076|
077| bname = path.basename(filename)
078| fname = path.splitext(filename)[0]+'.html'
079| fn = path.join(fpath,fname) if fpath else fname
080| fp = open(fn, mode='w', encoding='utf-8')
081| else:
082|
083| bname = '[stream]'
084| fp = fpath
085| try:
086| fp.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n')
087| fp.write('<html>\n')
088| fp.write('<head>\n')
089| fp.write('<title>%s</title>\n' % bname)
090| fp.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n')
091| fp.write('<style type="text/css">\n')
092| for name in Styles:
093| fp.write('.%s {%s}\n' % (name,Styles[name]))
094| fp.write('</style>\n')
095| fp.write('</head>\n')
096| fp.write('<body>\n')
097| fp.write('<h1>%s</h1>\n' % bname)
098| fp.write('<hr>\n')
099| ccursor = 0
100| linenbr = 1
101| fp.write(html_eol(html_div, linenbr))
102| for tt,ts,rc0,rc1,ln in toks:
103| ttn = tok_name[tt].lower()
104|
105| if ttn in ['encoding', 'indent', 'dedent', 'endmarker']:
106| continue
107|
108| if ttn in ['newline', 'nl']:
109| ccursor = 0
110| linenbr += 1
111| fp.write(html_eol(html_br, linenbr))
112| continue
113|
114| if ttn == 'name':
115| if ts in Keywords:
116| ttn = 'keyword'
117| elif ts in Functions:
118| ttn = 'function'
119|
120| if (ttn == 'string') and (6 <= len(ts)):
121| if ts[0:3] == ts[-3:]:
122| ttn = 'docstr'
123|
124| if ccursor < rc0[1]:
125|
126| fp.write(' '*(rc0[1]-ccursor))
127|
128| ts = ts.replace('&','&')
129| ts = ts.replace('<','<')
130| ts = ts.replace('>','>')
131| ts = ts.replace('"','"')
132| if ttn == 'docstr':
133| ts = ts.replace(' ',' ')
134| ts = ts.replace('\r','')
135| ts = ts.replace('\n', html_eol(html_br, linenbr))
136|
137| fp.write(html_span % (ttn, ts))
138|
139| ccursor = rc1[1]
140| fp.write('</div>\n')
141| fp.write('<hr>\n')
142|
143|
144| fp.write('</body>\n')
145| fp.write('</html>\n')
146| fp.write('\n')
147| except:
148| raise
149| else:
150| if log:
151| log.info('wrote: %s' % (fn if filename else bname))
152| finally:
153| if filename:
154| fp.close()
155|
156|
157| def write_fragment_html (toks, filename, fpath=None, line_nbrs=True, log=None):
158| '''Write HTML Output Fragment (content DIV block only).
158| args:
158| toks list of Python Tokens
158| filename filename of output file (None: fpath is an open file object)
158| fpath pathname of output file (None: filename is a full filename)
158| line_nbrs True or False (default=True)
158| log logger object (default=None)
158| '''
159| if log:
160| log.info('HTML: %s' % (filename if filename else '<stream>'))
161|
162| html_div = '<div style="font-family:monospace;font-size:8pt;line-height:1.2;padding:5px;border:1px solid black;margin:12pt 6pt;">\n%s'
163| html_span = '<span style="%s">%s</span>'
164| html_br = '<br>\n%s'
165| def html_eol (htm,ln):
166| if line_nbrs:
167| html_lnbr = '<span style="%s">%03d| </span>' % (Styles['linenbr'],ln)
168| return htm % html_lnbr
169| return htm % ''
170|
171| if filename:
172|
173| fname = path.splitext(filename)[0]+'.html'
174| fn = path.join(fpath, '%s.html' % fname) if fpath else fname
175| fp = open(fn, mode='w', encoding='utf-8')
176| else:
177|
178| fp = fpath
179| try:
180| ccursor = 0
181| linenbr = 1
182| fp.write(html_eol(html_div, linenbr))
183| for tt,ts,rc0,rc1,ln in toks:
184| ttn = tok_name[tt].lower()
185|
186| if ttn in ['encoding', 'indent', 'dedent', 'endmarker']:
187| continue
188|
189| if ttn in ['newline', 'nl']:
190| ccursor = 0
191| linenbr += 1
192| fp.write(html_eol(html_br, linenbr))
193| continue
194|
195| if ttn == 'name':
196| if ts in Keywords:
197| ttn = 'keyword'
198| elif ts in Functions:
199| ttn = 'function'
200|
201| if (ttn == 'string') and (6 <= len(ts)):
202| if ts[0:3] == ts[-3:]:
203| ttn = 'docstr'
204|
205| if ccursor < rc0[1]:
206|
207| fp.write(' '*(rc0[1]-ccursor))
208|
209| ts = ts.replace('&','&')
210| ts = ts.replace('<','<')
211| ts = ts.replace('>','>')
212| ts = ts.replace('"','"')
213| if ttn == 'docstr':
214| ts = ts.replace('\r','')
215| ts = ts.replace('\n', html_eol(html_br, linenbr))
216|
217| fp.write(html_span % (Styles[ttn],ts))
218|
219| ccursor = rc1[1]
220| fp.write('\n</div>\n')
221| except:
222| raise
223| else:
224| if log:
225| log.info('wrote: %s' % (fn if filename else '<stream>'))
226| finally:
227| if filename:
228| fp.close()
229|
230|
231| def write_output_listing (toks, filename, fpath=None, emit_source=False, log=None):
232| '''Write Listing Output File.
232| args:
232| toks list of Python Tokens
232| filename filename of output file
232| fpath pathname of output file (None: filename is a full filename)
232| emit_source True or False; include source code in output (default=False)
232| log logger object (default=None)
232| '''
233| cstr = lambda x: ' '.join(['%02x' % ord(ch) for ch in x])
234| fmt = '%4d[%3d:%3d|%3d:%3d] %-9s %-24s%s'
235| if log:
236| log.info('LIST: %s' % filename)
237|
238| fn = path.join(fpath, '%s.list' % filename) if fpath else filename
239| fp = open(fn, mode='w', encoding='utf-8')
240| try:
241|
242| for ix,tok in enumerate(toks):
243|
244| tt,ts,rc0,rc1,ln = tok
245|
246| ttn = tok_name[tt].lower()
247|
248| ts = cstr(ts) if ttn in ['nl','newline'] else ts
249|
250| ts = ts.replace(' ','-')
251|
252| ls = ('| %s' % ln.rstrip()) if emit_source else ''
253|
254| out = (ix+1, rc0[0],rc0[1], rc1[0],rc1[1], ttn,ts,ls)
255| print(fmt % out, file=fp)
256| print(file=fp)
257| except:
258| raise
259| else:
260| if log:
261| log.info('wrote: %s' % fn)
262| finally:
263| fp.close()
264|
265|
266| def parse_python (filename, fpath=None, log=None):
267| '''Tokenize Python Source File.
267| args:
267| filename filename of output file
267| fpath pathname of output file (None: filename is a full filename)
267| log logger object (default=None)
267| '''
268| if log:
269| log.info('Parse-Python: %s' % filename)
270|
271| fn = path.join(fpath, filename) if fpath else filename
272| fp = open(fn, mode='rb')
273| try:
274| toks = list(tokenize(fp.readline))
275| except:
276| raise
277| else:
278| if log:
279| log.info('read: %s' % fn)
280| finally:
281| fp.close()
282| return toks
283|
284|
285| def python_to_html_file (*filenames, log=None):
286| '''Python to HTML. Create HTML webpage from Python source file.
286| args:
286| filenames full filenames of output files
286| log logger object (default=None)
286| '''
287| for filename in filenames:
288| if log:
289| log.info('File2HTML: %s' % filename)
290|
291| toks = parse_python(filename, fpath=None)
292| write_output_html(toks, filename, fpath=None)
293| if log:
294| log.info()
295|
296|
297| def python_to_html_frag (*filenames, log=None):
298| '''Python to HTML. Create HTML fragment from Python source file.
298| args:
298| filenames full filenames of output files
298| log logger object (default=None)
298| '''
299| for filename in filenames:
300| if log:
301| log.info('File2HTML: %s' % filename)
302|
303| toks = parse_python(filename, fpath=None)
304| write_fragment_html(toks, filename, fpath=None, line_nbrs=True)
305| if log:
306| log.info()
307|
308|
309|
310| class TextParser (object):
311| '''(Recursive Descent) Parser class.'''
312| SpclWords = ['self', 'other', 'this', 'that']
313| SpcChr = ' '
314| TabChr = ' ' * 4
315|
316| class TextSource (object):
317| '''Text Source class.'''
318| def __init__ (self, txt):
319| '''New instance requires a string.'''
320| self.src = txt
321| self.cp = 0
322|
323| def rewind (self):
324| '''Restart text source.'''
325| self.cp = 0
326|
327| def get_ch (self):
328| '''Get next character.'''
329| if self.cp < len(self.src):
330| ch = self.src[self.cp]
331| self.cp += 1
332| return ch
333| return None
334|
335| def unget_ch (self):
336| '''Unget next character.'''
337| if 0 < self.cp:
338| self.cp -= 1
339|
340| def __init__ (self, txt):
341| '''New parser instance.'''
342| self.src = TextParser.TextSource(txt)
343| self.content = []
344| self.buf = ''
345| self.content.append('<pre style="background-image:url(/img/bg_computer_paper.png)">')
346| self._parse()
347| self.content.append('</pre>')
348| self.content.append(EOL)
349|
350| def __call__ (self):
351| return ''.join(self.content)
352|
353| def _parse (self):
354| while True:
355| ch = self.src.get_ch()
356| if not ch:
357| break
358| if ch == ' ':
359| self.content.append(self.SpcChr)
360| continue
361| if ch == '\t':
362| self.content.append(self.TabChr)
363| continue
364| if ch == '<':
365| self.content.append('<')
366| continue
367| if ch == '>':
368| self.content.append('>')
369| continue
370| if ch == '&':
371| self.content.append('&')
372| continue
373| if ch == ':':
374| self.content.append('<strong>:</strong>')
375| continue
376| if (ch == '"') or (ch == "'"):
377| self._quoted_string(ch)
378| continue
379| if ch == '#':
380| self._line_comment(ch)
381| continue
382| if ch.isdigit():
383| self._number(ch)
384| continue
385| if ch.isalpha() or (ch == '_'):
386| self._keyword(ch)
387| continue
388| self.content.append(ch)
389|
390| def _keyword (self, ch):
391| '''Parse keyword.'''
392| self.buf = ch
393| ch = self.src.get_ch()
394| while ch and (ch.isalnum() or (ch == '_')):
395| self.buf += ch
396| ch = self.src.get_ch()
397|
398| if ch:
399| self.src.unget_ch()
400|
401| if self.buf in self.SpclWords:
402| self.content.append('<span class="Special">%s</span>' % self.buf)
403| return
404| if iskeyword(self.buf):
405| self.content.append('<span class="Keyword">%s</span>' % self.buf)
406| return
407| self.content.append('<span class="Userdef">%s</span>' % self.buf)
408|
409| def _number (self, ch):
410| '''Parse number.'''
411| self.buf = ch
412| ch = self.src.get_ch()
413| while ch and ch.isdigit():
414| self.buf += ch
415| ch = self.src.get_ch()
416|
417| if ch:
418| self.src.unget_ch()
419| self.content.append('<span class="Number">%s</span>' % self.buf)
420|
421| def _line_comment (self, ch):
422| '''Parse comment (to end of line).'''
423| self.buf = ch
424| ch = self.src.get_ch()
425| while ch and (ch not in ['\r','\n']):
426| self.buf += ch
427| ch = self.src.get_ch()
428|
429| if ch:
430| self.src.unget_ch()
431| self.content.append('<span class="Comment">%s</span>' % self.buf)
432|
433| def _quoted_string (self, ch):
434| '''Parse quoted string.'''
435| ch1 = ch
436| ch2 = self.src.get_ch()
437| if ch2 == ch1:
438| ch3 = self.src.get_ch()
439| if ch3 == ch2:
440| self._triple_quoted_text(ch)
441| return
442|
443| self.src.unget_ch()
444|
445| self.content.append('<span class="String">%s%s</span>' % (ch1,ch2))
446| return
447|
448| self.buf = ch1
449| self.buf += self._htmlize(ch2)
450| ch = self.src.get_ch()
451| while ch and (ch != ch1):
452| self.buf += self._htmlize(ch)
453| ch = self.src.get_ch()
454|
455| if ch:
456| self.buf += ch
457| self.content.append('<span class="String">%s</span>' % self.buf)
458|
459| def _triple_quoted_text (self, ch):
460| '''Parse triple-quoted string.'''
461| self.buf = ch1 = ch * 3
462| ch = self.src.get_ch()
463| while ch:
464| self.buf += self._htmlize(ch)
465| if self.buf[-3:] == ch1:
466| break
467| ch = self.src.get_ch()
468| self.content.append('<span class="TripleQuote">%s</span>' % self.buf)
469|
470| def _htmlize (self, ch):
471| '''Handle characters HTML considers special.'''
472| if ch == '<': return '<'
473| if ch == '>': return '>'
474| if ch == '&': return '&'
475| return ch
476|
477|
478|
479| def python_to_html (py_filename, html_filename, log=None):
480| '''Python to HTML. Create HTML webpage from Python source file.
480| args:
480| py_filename Python filename to read
480| html_filename HTML filename to write
480| log logger object (default: None)
480| '''
481| if log:
482| log.info('Python-2-HTML: py=%s' % py_filename)
483| log.info('Python-2-HTML: html=%s' % html_filename)
484|
485|
486| fo = textfile(py_filename)
487| tp = TextParser(fo.data)
488|
489|
490| pg = WebPage(fo.filename, h2='Python Page', css=CssFiles)
491| pg.add(tp())
492|
493| fp = open(html_filename, mode='w', encoding='utf-8')
494| try:
495| pg.write(fp)
496| except:
497| raise
498| else:
499| if log:
500| log.info('wrote: %s' % path.basename(html_filename))
501| finally:
502| fp.close()
503|
504|
505|
506| H1 = 'Sonnack/Python'
507| H2 = 'Module Docs'
508| H3 = '<h3>%s</h3>'
509| H4 = '<h4 class="%s"><span style="color:#666666;font-weight:normal;">%s</span> %s</h4>'
510| CSS = ['/basic.css', 'docs.css']
511| LI = '<li><a href="%s.html">%s</a> %s</li>'
512|
513| def document_module (bag, moduleName, log=None):
514| ''' Document Module. '''
515| m = __import__(moduleName)
516| h = m.__doc__ if hasattr(m,'__doc__') else None
517| h = escape(h.strip()) if h else '(no Module Doc)'
518|
519|
520| d = []
521| for k in m.__dict__:
522|
523| obj = m.__dict__[k]
524|
525|
526|
527| mod_name = obj.__module__ if hasattr(obj,'__module__') else ''
528| if mod_name != m.__name__:
529| continue
530|
531|
532| obj_name = obj.__name__ if hasattr(obj,'__name__') else ''
533| obj_doc = obj.__doc__ if hasattr(obj,'__doc__') else ''
534| obj_type = type(obj).__name__
535| if obj_name == '<lambda>':
536| obj_type = 'lambda'
537|
538|
539| t = (k, obj_type, obj_name, obj_doc)
540| d.append(t)
541|
542|
543| fn = path.join(bag['htmlpath'], '%s.html' % moduleName)
544| pg = WebPage(bag['indextitle'], h1=H1, h2=H2, css=CSS, log=log)
545| pg.add(H3 % moduleName)
546| pg.add('<pre class="ModuleDoc">%s</pre>' % h)
547| for t in sorted(d, key=lambda x: (x[1],x[0])):
548| pg.add(H4 % (t[1], t[1], t[0]))
549| if t[1] not in ['function','type']:
550| continue
551| if t[3]:
552| pg.add('<pre class="ObjectDoc">%s</pre>' % escape(t[3].strip()))
553|
554| pg.save(fn)
555|
556| ix = h.find('.')
557| return (h if ix<0 else h[:ix])
558|
559|
560| def document_module_list (bag, log=None):
561| '''Given a configuration bag, document the modules listed.'''
562|
563| syspath.extend(bag['modpaths'])
564| if log:
565| log.debug('USERNAME: "%s"' % environ.get('USERNAME','<none>'))
566| log.debug('USERPROFILE: "%s"' % environ.get('USERPROFILE','<none>'))
567| log.debug('HOMEPATH: "%s"' % environ.get('HOMEPATH','<none>'))
568| log.debug('HOMEDRIVE: "%s"' % environ.get('HOMEDRIVE','<none>'))
569| log.debug()
570|
571|
572| fn = path.join(bag['htmlpath'], 'index_%s.html' % bag['name'])
573| pg = WebPage(bag['indextitle'], h1=H1, h2=H2, css=CSS, log=log)
574| pg.add('<ul>')
575|
576| for mod_name in bag['modlist']:
577| if log:log.info(mod_name)
578|
579| s = document_module(bag, mod_name)
580| pg.add(LI % (mod_name, mod_name, s))
581| pg.add('</ul>')
582|
583| pg.save(fn)
584|
585|
586|
587| '''eof'''
588|