man: make scripts Python2 compatible again.

My last commits broke functionality for Python2, but it's relatively
simple to fix.

open() becomes io.open() -- it effectively does nothing for Python3,
but for Python2 it uses a backported version of the open() call.

Python2 uses bytes and strings interchangably, but I needed to use
stdout.sys.buffer for writing arbitrary bytes data to stdout.
Conditionally call the appropriate stream depending on Python version.
This commit is contained in:
Mike Swanson 2017-01-21 07:13:08 -08:00
parent d0c36735aa
commit 765f864d84
2 changed files with 16 additions and 6 deletions

View file

@ -28,6 +28,7 @@
# CONFIG_VARIABLE_INT(my_variable, c_variable),
#
import io
import sys
import os
import re
@ -36,6 +37,14 @@ import getopt
INCLUDE_STATEMENT_RE = re.compile("@include\s+(\S+)")
# Use appropriate stdout function for Python 2 or 3
def stdout(buf):
if sys.version_info.major < 3:
sys.stdout.write(buf)
else:
sys.stdout.buffer.write(buf)
# Find the maximum width of a list of parameters (for plain text output)
def parameter_list_width(params):
@ -300,7 +309,7 @@ class Parameter:
# Read list of wiki pages
def read_wikipages():
f = open("wikipages", encoding='UTF-8')
f = io.open("wikipages", encoding='UTF-8')
try:
for line in f:
@ -356,7 +365,7 @@ def process_file(file):
current_config_file = None
f = open(file, encoding='UTF-8')
f = io.open(file, encoding='UTF-8')
try:
param = None
@ -422,7 +431,7 @@ def process_files(path):
process_file(path)
def print_template(template_file, content):
f = open(template_file, encoding='UTF-8')
f = io.open(template_file, encoding='UTF-8')
try:
for line in f:
@ -432,7 +441,7 @@ def print_template(template_file, content):
print_template(filename, content)
else:
line = line.replace("@content", content)
sys.stdout.buffer.write(line.rstrip().encode('UTF-8') + b'\n')
stdout(line.rstrip().encode('UTF-8') + b'\n')
finally:
f.close()
@ -452,7 +461,7 @@ def wiki_output(targets, template):
read_wikipages()
for t in targets:
sys.stdout.buffer.write(t.wiki_output().encode('UTF-8') + b'\n')
stdout(t.wiki_output().encode('UTF-8') + b'\n')
def plaintext_output(targets, template_file):

View file

@ -40,6 +40,7 @@
#
import collections
import io
import sys
import re
@ -76,7 +77,7 @@ def parse_stream(stream):
raise Exception("Mismatched #if in '%s'" % stream.name)
def parse_file(filename):
f = open(filename, encoding='UTF-8')
f = io.open(filename, encoding='UTF-8')
try:
parse_stream(f)