""" DocTestQuiz by Andre Roberge """ import cherrypy import os from tempfile import gettempdir TMP_DIR = gettempdir() EXAMPLES = [ """ >>> p = Animal() >>> p.name '' >>> p.friends [] """, """ >>> p = Animal('Pooh') >>> p.name 'Pooh' >>> p.addFriend('Piglet') >>> p.friends ['Piglet'] """ ] title = 'Learn Python' instructions = 'Write just enough Python code to make '+\ 'the following DocTests pass:' begin_output = "The result is :
"
end_output = "
" triple_quote = "\'\'\'" example = 0 success = False class PythonRunner(object): def header(self): return ''' %s

%s

%s

%s
''' % (title, title, instructions, EXAMPLES[example]) def footer(self): return ''' ''' def index(self, code=None): global success, example count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count if success: success = False count = 1 example += 1 if code is None: code = '' output = '' if count > 1: cherrypy.session['code'] = triple_quote + EXAMPLES[example] + \ triple_quote + '\n'+ code tmp_filename = os.path.join(TMP_DIR, 'my_file.dat') f = open(tmp_filename, 'w') test_code = cherrypy.session['code'] + \ "\nimport doctest\ndoctest.testmod()" f.write(test_code) f.close() f_in, f_out = os.popen4("python %s"%tmp_filename) result = '' for line in f_out.readlines(): result += line if result == '': output = "

Success!

" button1 = '' button2 = '
' success = True else: output = begin_output + result + end_output button1 = '' button2 = '' else: button1 = '' button2 = '' if example == len(EXAMPLES): return "

All done!

" return self.header()+''' Type in your Python code.

%s

%s %s ''' % (code, button1, output + self.footer(), button2) index.exposed = True cherrypy.root = PythonRunner() cherrypy.config.update({'session_filter.on': True}) if __name__ == '__main__': cherrypy.config.update(file = 'tutorial.conf') cherrypy.server.start()