我正在为我的学生(我是导师)开发一个代码检查器。项目的要求是,他们编写一个使用print
关键字打印特定字符串的函数。我希望能够通过存储并匹配到列表(或类似的东西)来测试他们所打印的内容。基本设置如下:
def checker():
#run user code
do some other things like save and check error messages etc
现在,在这个checker
函数中,我希望能够跟踪打印出来的内容。在JavaScript中,我可以这样做:
var logs = [];
var hold_logger = console.log //saves the console.log so nothing gets ruined
console.log = function (x) { logs.push(x) };
现在当我运行学生的代码时,它不再在控制台打印,而是将值推送到logs
中。我想在Python 2.7中实现同样的效果。