python 将字符串转换为可执行代码

相信很多人都有这样的困惑,就是想将另外一个文件的传来的字符串转换为代码,然后百度,google,找了很久找到了c++, java的方法,就是没有python的解决方法,笔者决定写这篇博客帮助一下大家,其实很简单。那在这里我把自己的经历写出来把,笔者是一个小小的python程序员,一天技术总监要求我写一个代替print重定向的模块,这模块能把错误信息保存在一个文件上而不是仅仅打印出来,笔者在网上查找了资料,就用了Configarser模块(具体用法点击传送门Configarser),看了一下资料后,马上入手开始写代码。我的配置文件如下:

log.cfg

[console]
console = logging.getLogger().addHandler(console)

[grade]
;grade = console.setLevel(logging.CRITICAL)
;grade = console.setLevel(logging.ERROR)
;grade = console.setLevel(logging.WARNING)
;grade = console.setLevel(logging.INFO)
grade = console.setLevel(logging.DEBUG)
;grade = console.setLevel(logging.NOTSET)

[savefile]
# write error infomation to file
file = logging.CRITICAL

# don't save error infomation to file
;file = logging.NOTSET


[default]
console = 0
grade = console.setLevel(logging.DEBUG)
file = logging.NOTSET

我需要把配置文件log.cfg中grade = console.setLevel(logging.DEBUG)传到main上当代码,可是传过来的是字符串来的,这可花了我不少时间,最后才发现可以用eval()来解决这个问题,我看了很多eval的资料都没有说到eval()可以把字符串变成可执行代码的作用。最后贴上代码

main.py


从log.cfg传过来的字符串直接当代码使用了。

猜你喜欢

转载自blog.csdn.net/weixin_40894428/article/details/80762138