在我的 Python 程序中,我想通过将字符串参数转换为变量名来动态加载模块并访问模块的变量。
用例
我在 SD 卡上有不同的字体,它们是 python 文件,还有一个显示函数,它在需要显示字符时加载字体。
我的字体文件的示例:
# 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 ........
此外,还有一个 Writer 类将字体呈现给显示器:
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
有谁知道如何将正确字体的查询字符的正确值保存到变量宽度、高度和位图中?
我只想在需要时动态加载字体,并提供通过将新的 .py 字体文件放入文件夹来添加新字体的可能性。
提前致谢。