1
0
Fork 0
mirror of https://github.com/opentx/opentx.git synced 2025-07-21 15:25:17 +03:00

Use with open(...) as ...: context managers

Instead of manually opening and closes file objects, use the context
manager that will properly handle opening and closing files for us, even
in the event of some error
This commit is contained in:
Sean Vig 2015-12-13 18:57:36 -06:00
parent 82c3230981
commit 4bd90d79d0
7 changed files with 234 additions and 249 deletions

View file

@ -8,12 +8,14 @@ import glob
def addLine(filename, newline, after): def addLine(filename, newline, after):
print(filename, newline) print(filename, newline)
lines = file(filename, 'r').readlines() with open(filename, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines): for i, line in enumerate(lines):
if after in line: if after in line:
lines.insert(i + 1, newline + '\n') lines.insert(i + 1, newline + '\n')
break break
file(filename, 'w').writelines(lines) with open(filename, 'w') as f:
f.writelines(lines)
def modifyTranslations(constant, translation, after): def modifyTranslations(constant, translation, after):

View file

@ -1,22 +1,20 @@
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import division
import sys import sys
filename = sys.argv[1] filename = sys.argv[1]
fileout = sys.argv[2] fileout = sys.argv[2]
fr = open(filename, "rb") # Read entire file
fw = open(fileout, "w") with open(filename, "rb") as fr:
sts = fr.read()
# Parse into chunks of 16 bytes
sts = [sts[i * 16:(i + 1) * 16] for i in range(len(sts) // 16)]
st = fr.read(16) with open(fileout, "w") as fw:
for st in sts:
while st: for b in st:
for b in st: fw.write("0x%02x," % ord(b))
fw.write("0x%02x," % ord(b)) fw.write("\n")
fw.write("\n") fw.write("\n")
st = fr.read(16)
fw.write("\n")
fw.close()
fr.close()

View file

@ -13,9 +13,8 @@ def writeheader(filename, header):
header should be a list of strings header should be a list of strings
skip should be a regex skip should be a regex
""" """
f = open(filename,"r") with open(filename, "r") as f:
inpt =f.readlines() inpt = f.readlines()
f.close()
output = [] output = []
# comment out the next 3 lines if you don't wish to preserve shebangs # comment out the next 3 lines if you don't wish to preserve shebangs
@ -36,18 +35,16 @@ def writeheader(filename, header):
for line in inpt: for line in inpt:
output.append(line) output.append(line)
try: try:
f = open(filename,'w') with open(filename, 'w') as f:
f.writelines(output) f.writelines(output)
f.close()
print("added header to %s" % filename) print("added header to %s" % filename)
except IOError as err: except IOError as err:
print("something went wrong trying to add header to %s: %s" % (filename, err)) print("something went wrong trying to add header to %s: %s" % (filename, err))
def main(args=sys.argv): def main(args=sys.argv):
headerfile = open(args[1]) with open(args[1]) as headerfile:
header = headerfile.readlines() header = headerfile.readlines()
headerfile.close()
writeheader(args[2], header) writeheader(args[2], header)

View file

@ -88,15 +88,14 @@ def createFontBitmap(filename, fontname, fontsize, fontbold, foreground, backgro
painter.end() painter.end()
image.save(filename + ".png") image.save(filename + ".png")
if coordsfile: if coordsfile:
f = file(filename + ".specs", "w") with open(filename + ".specs", "w") as f:
f.write("{ ") f.write("{ ")
f.write(",".join(str(tmp) for tmp in coords)) f.write(",".join(str(tmp) for tmp in coords))
if extraWidth: if extraWidth:
for i in range(1, 14): for i in range(1, 14):
f.write(", %d" % (int(coords[-1]) + i * (extraWidth / 12))) f.write(", %d" % (int(coords[-1]) + i * (extraWidth / 12)))
# f.write(file("fonts/extra_%dpx.specs" % fontsize).read()) # f.write(file("fonts/extra_%dpx.specs" % fontsize).read())
f.write(" }") f.write(" }")
f.close()
return coords return coords
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -16,140 +16,139 @@ def writeSize(f, width, height):
f.write("%d,%d,\n" % (width, height)) f.write("%d,%d,\n" % (width, height))
f = open(sys.argv[2], "w") with open(sys.argv[2], "w") as f:
lcdwidth = int(sys.argv[3])
lcdwidth = int(sys.argv[3]) if len(sys.argv) > 4:
what = sys.argv[4]
else:
for s in ("03x05", "04x06", "05x07", "08x10", "10x14", "22x38"):
if s in sys.argv[2]:
what = s
break
if len(sys.argv) > 4: if what == "1bit":
what = sys.argv[4] rows = 1
else: if len(sys.argv) > 5:
for s in ("03x05", "04x06", "05x07", "08x10", "10x14", "22x38"): rows = int(sys.argv[5])
if s in sys.argv[2]: writeSize(f, width, height // rows)
what = s for y in range(0, height, 8):
break for x in range(width):
if what == "1bit":
rows = 1
if len(sys.argv) > 5:
rows = int(sys.argv[5])
writeSize(f, width, height // rows)
for y in range(0, height, 8):
for x in range(width):
value = 0
for z in range(8):
if y + z < height and image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
f.write("0x%02x," % value)
f.write("\n")
elif what == "4/4/4/4":
colors = []
f.write("%d,%d,\n" % (width, height))
for y in range(height):
for x in range(width):
pixel = image.pixel(x, y)
f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel) // 16, Qt.qRed(pixel) // 16, Qt.qGreen(pixel) // 16, Qt.qBlue(pixel) // 16))
f.write("\n")
elif what == "5/6/5/8":
colors = []
writeSize(f, width, height)
for y in range(height):
for x in range(width):
pixel = image.pixel(x, y)
val = ((Qt.qRed(pixel) >> 3) << 11) + ((Qt.qGreen(pixel) >> 2) << 5) + ((Qt.qBlue(pixel) >> 3) << 0)
# f.write("%d,%d,%d," % (val%256, val/256, Qt.qAlpha(pixel) >> 4))
f.write("%d,%d," % (val % 256, val // 256))
f.write("\n")
elif what == "4bits":
colors = []
writeSize(f, width, height)
for y in range(0, height, 2):
for x in range(width):
value = 0xFF
gray1 = Qt.qGray(image.pixel(x, y))
if y + 1 < height:
gray2 = Qt.qGray(image.pixel(x, y + 1))
else:
gray2 = Qt.qRgb(255, 255, 255)
for i in range(4):
if (gray1 & (1 << (4 + i))):
value -= 1 << i
if (gray2 & (1 << (4 + i))):
value -= 1 << (4 + i)
f.write("0x%02x," % value)
f.write("\n")
elif what == "8bits":
colors = []
writeSize(f, width, height)
for y in range(height):
for x in range(width):
value = Qt.qGray(image.pixel(x, y))
value = 0x0f - (value >> 4)
f.write("0x%02x," % value)
f.write("\n")
elif what == "03x05":
for y in range(0, height, 5):
for x in range(width):
value = 0
for z in range(5):
if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
f.write("0x%02x," % value)
f.write("\n")
elif what == "04x06":
for y in range(0, height, 7):
for x in range(width):
value = 0
for z in range(7):
if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
if value == 0x7f:
value = 0xff
f.write("0x%02x," % value)
f.write("\n")
elif what == "05x07":
for y in range(0, height, 8):
for x in range(width):
value = 0
for z in range(8):
if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
f.write("0x%02x," % value)
f.write("\n")
elif what == "08x10":
for y in range(0, height, 12):
for x in range(width):
skip = True
for l in range(0, 12, 8):
value = 0 value = 0
for z in range(8): for z in range(8):
if l + z < 12: if y + z < height and image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): value += 1 << z
value += 1 << z f.write("0x%02x," % value)
else: f.write("\n")
skip = False elif what == "4/4/4/4":
if skip and l == 8: colors = []
f.write("%d,%d,\n" % (width, height))
for y in range(height):
for x in range(width):
pixel = image.pixel(x, y)
f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel) // 16, Qt.qRed(pixel) // 16, Qt.qGreen(pixel) // 16, Qt.qBlue(pixel) // 16))
f.write("\n")
elif what == "5/6/5/8":
colors = []
writeSize(f, width, height)
for y in range(height):
for x in range(width):
pixel = image.pixel(x, y)
val = ((Qt.qRed(pixel) >> 3) << 11) + ((Qt.qGreen(pixel) >> 2) << 5) + ((Qt.qBlue(pixel) >> 3) << 0)
# f.write("%d,%d,%d," % (val%256, val/256, Qt.qAlpha(pixel) >> 4))
f.write("%d,%d," % (val % 256, val // 256))
f.write("\n")
elif what == "4bits":
colors = []
writeSize(f, width, height)
for y in range(0, height, 2):
for x in range(width):
value = 0xFF
gray1 = Qt.qGray(image.pixel(x, y))
if y + 1 < height:
gray2 = Qt.qGray(image.pixel(x, y + 1))
else:
gray2 = Qt.qRgb(255, 255, 255)
for i in range(4):
if (gray1 & (1 << (4 + i))):
value -= 1 << i
if (gray2 & (1 << (4 + i))):
value -= 1 << (4 + i)
f.write("0x%02x," % value)
f.write("\n")
elif what == "8bits":
colors = []
writeSize(f, width, height)
for y in range(height):
for x in range(width):
value = Qt.qGray(image.pixel(x, y))
value = 0x0f - (value >> 4)
f.write("0x%02x," % value)
f.write("\n")
elif what == "03x05":
for y in range(0, height, 5):
for x in range(width):
value = 0
for z in range(5):
if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
f.write("0x%02x," % value)
f.write("\n")
elif what == "04x06":
for y in range(0, height, 7):
for x in range(width):
value = 0
for z in range(7):
if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
if value == 0x7f:
value = 0xff value = 0xff
f.write("0x%02x," % value) f.write("0x%02x," % value)
f.write("\n") f.write("\n")
elif what == "10x14": elif what == "05x07":
for y in range(0, height, 16): for y in range(0, height, 8):
for x in range(width): for x in range(width):
for l in range(0, 16, 8):
value = 0 value = 0
for z in range(8): for z in range(8):
if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0):
value += 1 << z value += 1 << z
f.write("0x%02x," % value) f.write("0x%02x," % value)
f.write("\n") f.write("\n")
elif what == "22x38": elif what == "08x10":
for y in range(0, height, 40): for y in range(0, height, 12):
for x in range(width): for x in range(width):
for l in range(0, 40, 8): skip = True
value = 0 for l in range(0, 12, 8):
for z in range(8): value = 0
if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): for z in range(8):
value += 1 << z if l + z < 12:
f.write("0x%02x," % value) if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0):
f.write("\n") value += 1 << z
else: else:
print("wrong argument", sys.argv[4]) skip = False
if skip and l == 8:
value = 0xff
f.write("0x%02x," % value)
f.write("\n")
elif what == "10x14":
for y in range(0, height, 16):
for x in range(width):
for l in range(0, 16, 8):
value = 0
for z in range(8):
if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
f.write("0x%02x," % value)
f.write("\n")
elif what == "22x38":
for y in range(0, height, 40):
for x in range(width):
for l in range(0, 40, 8):
value = 0
for z in range(8):
if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0):
value += 1 << z
f.write("0x%02x," % value)
f.write("\n")
else:
print("wrong argument", sys.argv[4])

View file

@ -6,9 +6,8 @@ import sys
import os import os
for filename in sys.argv[1:]: for filename in sys.argv[1:]:
f = file(filename, "r") with open(filename, "r") as f:
lines = f.readlines() lines = f.readlines()
f.close()
newguard = "_" + os.path.basename(filename).upper().replace(".", "_") + "_" newguard = "_" + os.path.basename(filename).upper().replace(".", "_") + "_"
@ -24,7 +23,6 @@ for filename in sys.argv[1:]:
while not lines[end].strip().startswith("#endif"): while not lines[end].strip().startswith("#endif"):
end -= 1 end -= 1
lines[end] = "#endif // %s\n" % newguard lines[end] = "#endif // %s\n" % newguard
f = file(filename, "w") with open(filename, "w") as f:
f.write("".join(lines)) f.write("".join(lines))
f.close()
break break

View file

@ -66,86 +66,80 @@ print("Output file %s" % outputFile)
if docFile: if docFile:
print("Documentation file %s" % docFile) print("Documentation file %s" % docFile)
np = open(inputFile, "r") with open(inputFile, "r") as inp:
while True:
line = inp.readline()
if len(line) == 0:
break
line = line.strip('\r\n')
line = line.strip()
# print "line: %s" % line
while True: parts = line.split('LEXP')
line = inp.readline() # print parts
if len(line) == 0: if len(parts) != 2:
break print("Wrong line: %s" % line)
line = line.strip('\r\n') continue
line = line.strip() cmd = 'LEXP' + parts[1]
# print "line: %s" % line cnst = parts[0].rstrip(', ')
if cnst.find('=') != -1:
# constant contains =
cnst = cnst.split('=')[0].strip()
# print "Found constant %s with command: %s" % (cnst, cmd)
try:
CONSTANT_VALUE = cnst
# if CONSTANT_VALUE in dups_cnst:
# print "WARNING: Duplicate CONSTANT_VALUE found: %s" % CONSTANT_VALUE
# warning = True
# continue
# dups_cnst.append(CONSTANT_VALUE)
# print cmd
eval(cmd)
except:
print("ERROR: problem with the definition: %s" % line)
traceback.print_exc()
error = True
parts = line.split('LEXP') with open(outputFile, "w") as out:
# print parts out.write("//This file was generated by luaexport.py script on %s for OpenTX version %s\n\n\n"
if len(parts) != 2: % (time.asctime(), version))
print("Wrong line: %s" % line)
continue
cmd = 'LEXP' + parts[1]
cnst = parts[0].rstrip(', ')
if cnst.find('=') != -1:
# constant contains =
cnst = cnst.split('=')[0].strip()
# print "Found constant %s with command: %s" % (cnst, cmd)
try:
CONSTANT_VALUE = cnst
# if CONSTANT_VALUE in dups_cnst:
# print "WARNING: Duplicate CONSTANT_VALUE found: %s" % CONSTANT_VALUE
# warning = True
# continue
# dups_cnst.append(CONSTANT_VALUE)
# print cmd
eval(cmd)
except:
print("ERROR: problem with the definition: %s" % line)
traceback.print_exc()
error = True
inp.close() header = """
struct LuaSingleField {
uint16_t id;
const char * name;
const char * desc;
};
out = open(outputFile, "w") struct LuaMultipleField {
uint16_t id;
const char * name;
const char * desc;
uint8_t count;
};
out.write("//This file was generated by luaexport.py script on %s for OpenTX version %s\n\n\n" """
% (time.asctime(), version)) out.write(header)
header = """ out.write("""
struct LuaSingleField { // The list of Lua fields
uint16_t id; // this aray is alphabetically sorted by the second field (name)
const char * name; const LuaSingleField luaSingleFields[] = {
const char * desc; """)
}; exports.sort(key=lambda x: x[1]) # sort by name
data = [" {%s, \"%s\", \"%s\"}" % export for export in exports]
out.write(",\n".join(data))
out.write("\n};\n\n")
print("Generated %d items in luaFields[]" % len(exports))
struct LuaMultipleField { out.write("""
uint16_t id; // The list of Lua fields that have a range of values
const char * name; const LuaMultipleField luaMultipleFields[] = {
const char * desc; """)
uint8_t count; data = [" {%s, \"%s\", \"%s\", %d}" % export for export in exports_multiple]
}; out.write(",\n".join(data))
out.write("\n};\n\n")
""" print("Generated %d items in luaMultipleFields[]" % len(exports_multiple))
out.write(header)
out.write("""
// The list of Lua fields
// this aray is alphabetically sorted by the second field (name)
const LuaSingleField luaSingleFields[] = {
""")
exports.sort(key=lambda x: x[1]) # sort by name
data = [" {%s, \"%s\", \"%s\"}" % export for export in exports]
out.write(",\n".join(data))
out.write("\n};\n\n")
print("Generated %d items in luaFields[]" % len(exports))
out.write("""
// The list of Lua fields that have a range of values
const LuaMultipleField luaMultipleFields[] = {
""")
data = [" {%s, \"%s\", \"%s\", %d}" % export for export in exports_multiple]
out.write(",\n".join(data))
out.write("\n};\n\n")
print("Generated %d items in luaMultipleFields[]" % len(exports_multiple))
out.close()
if docFile: if docFile:
# prepare fields # prepare fields
@ -160,16 +154,14 @@ if docFile:
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key[0])] alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key[0])]
all_exports.sort(key=alphanum_key) all_exports.sort(key=alphanum_key)
out = open(docFile, "w") with open(docFile, "w") as out:
out.write("Alphabetical list of Lua fields for OpenTX version %s\n\n\n" % version) out.write("Alphabetical list of Lua fields for OpenTX version %s\n\n\n" % version)
FIELD_NAME_WIDTH = 25 FIELD_NAME_WIDTH = 25
out.write("Field name%sField description\n" % (' ' * (FIELD_NAME_WIDTH - len('Field name')))) out.write("Field name%sField description\n" % (' ' * (FIELD_NAME_WIDTH - len('Field name'))))
out.write("----------------------------------------------\n") out.write("----------------------------------------------\n")
data = ["%s%s%s" % (name_, ' ' * (FIELD_NAME_WIDTH - len(name_)), desc_) for (name_, desc_) in all_exports] data = ["%s%s%s" % (name_, ' ' * (FIELD_NAME_WIDTH - len(name_)), desc_) for (name_, desc_) in all_exports]
out.write("\n".join(data)) out.write("\n".join(data))
out.write("\n") out.write("\n")
out.close()
if warning: if warning:
sys.exit(1) sys.exit(1)