cleanin up coding conventions

This commit is contained in:
q
2018-11-08 18:36:27 +02:00
parent 1a7855242c
commit c4b484a7b9
2 changed files with 111 additions and 74 deletions

View File

@@ -6,46 +6,56 @@ from argparse import ArgumentParser
def png2asc(inFile): def png2asc(inFile):
im=scipy.misc.imread(inFile) im = scipy.misc.imread(inFile)
for r in im: for r in im:
for c in r: for c in r:
if c>127: if c>127:
char="X" char = "X"
if c<128: if c<128:
char="." char = "."
if c==0: if c==0:
char=" " char = " "
sys.stdout.write(char) sys.stdout.write(char)
sys.stdout.write("\n") sys.stdout.write("\n")
def asc2png(inFile,outFile): def asc2png(inFile, outFile):
reader = open(inFile,'r') reader = open(inFile,'r')
coords=[] coords = []
max_c=0 max_c = 0
for r,row in enumerate(reader): for r,row in enumerate(reader):
for c,col in enumerate(row): for c,col in enumerate(row):
if col not in (' ','\n'): if col not in (' ', '\n'):
if col==".": if col == ".":
coords.append((r,c,127)) coords.append((r, c, 127))
else: else:
coords.append((r,c,255)) coords.append((r, c, 255))
max_c=max(max_c,c) max_c = max(max_c, c)
im=n.zeros( (r,max_c-1), dtype=n.uint8 ) im=n.zeros( (r, max_c-1), dtype = n.uint8 )
for c in coords: for c in coords:
im[c[0],c[1]]=c[2] im[c[0], c[1]] = c[2]
scipy.misc.imsave(outFile, im) scipy.misc.imsave(outFile, im)
if __name__ == "__main__":
parser=ArgumentParser(description="Convert image to ascii, or ascii to image. If only input is defined, it is assumed as image (PNG).") parser = ArgumentParser(
parser.add_argument('input', action="store") description = "Convert image to ascii, or ascii to image. If only input is defined, it is assumed as image (PNG)."
parser.add_argument('output', action="store", nargs='?') )
opts=parser.parse_args() parser.add_argument(
'input',
action = "store"
)
parser.add_argument(
'output',
action = "store",
nargs = '?'
)
opts = parser.parse_args()
if opts.output==None: if opts.output == None:
png2asc(opts.input) png2asc(opts.input)
else: else:
asc2png(opts.input,opts.output) asc2png(opts.input, opts.output)

View File

@@ -2,8 +2,10 @@
import sys,re,os import sys,re,os
from argparse import ArgumentParser from argparse import ArgumentParser
from argparse import RawTextHelpFormatter from argparse import RawTextHelpFormatter
def setup_options(): def setup_options():
parser=ArgumentParser(description="""Template Filler parser = ArgumentParser(
description="""Template Filler
=== Template example: === === Template example: ===
Hello [[name]]! Hello [[name]]!
@@ -12,62 +14,87 @@ def setup_options():
== Value file/Value pair example: == == Value file/Value pair example: ==
[[name]]=John [[name]]=John
[[letter]]=@letter.txt [[letter]]=@letter.txt
""",formatter_class=RawTextHelpFormatter) """,
parser.add_argument("-e",action="store_true",dest="env",default=False, formatter_class = RawTextHelpFormatter
help="Use the environment to replace ${env} style variables.") )
parser.add_argument("-f",action="store",dest="file", parser.add_argument(
help="File name to read keys/values.") "-e",
parser.add_argument("-p",action="append",dest="values",default=[], action = "store_true",
help="key=value pairs. This option may be issued several times.") dest = "env",
parser.add_argument('template', action="store", nargs='?', default = False,
help="Template file to be filled. If not defined, stdin used.") help = "Use the environment to replace ${env} style variables."
options=parser.parse_args() )
parser.add_argument(
"-f",
action = "store",
dest = "file",
help = "File name to read keys/values."
)
parser.add_argument(
"-p",
action = "append",
dest = "values",
default = [],
help = "key=value pairs. This option may be issued several times."
)
parser.add_argument(
'template',
action = "store",
nargs = '?',
help = "Template file to be filled. If not defined, stdin used."
)
options = parser.parse_args()
return options return options
def parse_file(filename): def parse_file(filename):
pairs=[] pairs = []
with open(filename,"r") as reader: with open(filename, "r") as reader:
for i,l in enumerate(reader): for i, l in enumerate(reader):
l=l.rstrip("\n\r") l = l.rstrip("\n\r")
if len(l)==0: if len(l) == 0:
continue continue
tokens = l.split('=', 1) tokens = l.split('=', 1)
if len(tokens)!=2: if len(tokens) != 2:
print("File %s:%i key=value pair '%s' does not parse"%(filename,i+1,l,)) print("File %s:%i key=value pair '%s' does not parse"%(
filename, i+1, l,
))
sys.exit(1) sys.exit(1)
pairs.append( (tokens[0], tokens[1].decode('string_escape')) ) pairs.append( (tokens[0], tokens[1].decode('string_escape')) )
return pairs return pairs
def parse_arguments(args): def parse_arguments(args):
pairs=[] pairs = []
for p in args: for p in args:
tokens = p.split('=', 1) tokens = p.split('=', 1)
if len(tokens)!=2: if len(tokens) != 2:
print("Argument key=value pair '%s' does not parse"%(p,)) print("Argument key=value pair '%s' does not parse"%(p,))
sys.exit(1) sys.exit(1)
pairs.append( (tokens[0], tokens[1].decode('string_escape')) ) pairs.append( (tokens[0], tokens[1].decode('string_escape')) )
return pairs return pairs
options=setup_options();
pairs=[] if __name__ == "__main__":
if options.file!=None: options = setup_options();
pairs.extend(parse_file(options.file)) pairs = []
pairs.extend(parse_arguments(options.values)) if options.file != None:
if options.template==None: pairs.extend(parse_file(options.file))
in_reader=sys.stdin pairs.extend(parse_arguments(options.values))
else: if options.template == None:
in_reader=open(options.template,'rb') in_reader = sys.stdin
for l in in_reader: else:
for p in pairs: in_reader = open(options.template, 'rb')
value=p[1] for l in in_reader:
if len(value)>0: for p in pairs:
if value[0]=="@": value = p[1]
value=open(value[1:],'rt').read() if len(value) > 0:
elif value[0:2]=="\\@": if value[0] == "@":
value=value[1:] value = open(value[1:], 'rt').read()
l=l.replace(p[0],value) elif value[0:2] == "\\@":
if options.env: value = value[1:]
var_list=[m.group(0) for m in re.finditer('\${[^ ]+}', l)] l = l.replace(p[0], value)
for v in var_list: if options.env:
l=l.replace(v,os.environ.get(v[:-1][2:],"")) var_list = [m.group(0) for m in re.finditer('\${[^ ]+}', l)]
sys.stdout.write(l) for v in var_list:
l = l.replace(v, os.environ.get(v[:-1][2:], ""))
sys.stdout.write(l)