In my Python programm I want to dynamically load modules and access variables of the module by converting a string parameter into a variable name.
Use Case
I have different Fonts on SD Card which are python files, and a display function which loads the font when needed to display the caracters.
Examples for my font file:
# arial14.py
# ch_(ASCII) = (widht), (height), [bitmask]
ch_33 = 3, 16, [0,0,0,0,0,0,0,0,0,1,1,1,1,1 ........
ch_34 = 5, 16, [0,0,0,0,0,0,0,0,0,0,0,0,0,0 ........
....
# arial20.py
ch_33 = 4, 22, [0,0,0,0,0,0,0,0,0,1,1,1,1,1 ........
ch_34 = 8, 22, [0,0,0,0,0,0,0,0,0,0,0,0,0,0 ........
Further, there is a Writer class which renders the fonts to the display:
class Writer(object):
def __init__(self):
try:
global arial14
import arial14
self.current_module = "arial14"
self.imported_fonts = []
self.imported_fonds.append(self.current_module)
except ImportError:
print("Error loading Font")
def setfont(self, fontname, fontsize):
modname = fontname+str(fontsize)
if modname not in self.importedfonts:
try:
exec("global" + modname)
exec("import" + modname) #import the font (works)
self.importedfonts.append(modname)
except ImportError:
print("Error loading Font")
return
else:
print(modname+" was already imported")
self.current_module = modname
print("Font is set now to: "+ self.current_module
## HERE COMES THE NON WORKING PART:
def putc_ascii(self, ch, xpos, ypos):
execline = "width, height, bitmap = "+ self.cur_mod+".ch_"+str(ch)
print(execline)
#this example.: width, height,bitmap = arial14.ch_55
width, height,bitmap = arial14.ch_32
print(width, height, bitmap) # values of arial14.ch_32 -> correct
exec (execline)
print(width, height, bitmap) # values of arial14.ch_32
# BUT VALUES OF arial14.ch_55 EXPECTED
Has anybody an idea how can I accomplish to save the correct values of the queried character of the correct font into the variables width, height and bitmap?
I want to load the Fonts dynamically only if needed, and offer the possibility to add new fonts by putting new .py font files into the folder.
Thanks in advance.