ui.cli: Import `readline` for more comfortable input() editing
[quizzer.git] / quizzer / ui / cli.py
1 try:
2     import readline as _readline
3 except ImportError as _readline_import_error:
4     _readline = None
5
6 from . import UserInterface
7
8
9 class CommandLineInterface (UserInterface):
10     def run(self):
11         while True:
12             question = self.get_question()
13             if not question:
14                 break
15             print(question.prompt)
16             while True:
17                 try:
18                     answer = input('? ')
19                 except EOFError:
20                     answer = 'quit'
21                 a = answer.strip().lower()
22                 if a in ['q', 'quit']:
23                     print()
24                     return
25                 if a in ['?', 'help']:
26                     print()
27                     print(question.prompt)
28                     print(question.help)
29                     continue
30                 break
31             correct = self.process_answer(question=question, answer=answer)
32             if correct:
33                 print('correct\n')
34             else:
35                 print('incorrect\n')
36
37     def display_results(self):
38         print('results:')
39         for question in self.quiz:
40             if question.id in self.answers:
41                 self.display_result(question=question)
42                 print()
43         self.display_totals()
44
45     def display_result(self, question):
46         answers = self.answers.get(question.id, [])
47         print('question:     {}'.format(question.prompt))
48         la = len(answers)
49         lc = len([a for a in answers if a['correct']])
50         print('answers: {}/{} ({:.2f})'.format(lc, la, float(lc)/la))
51         for answer in answers:
52             if answer['correct']:
53                 correct = 'correct'
54             else:
55                 correct = 'incorrect'
56             print('  you answered: {}'.format(answer['answer']))
57             print('     which was: {}'.format(correct))
58
59     def display_totals(self):
60         answered = self.answers.get_answered(questions=self.quiz)
61         correctly_answered = self.answers.get_correctly_answered(
62             questions=self.quiz)
63         la = len(answered)
64         lc = len(correctly_answered)
65         print('answered {} of {} questions'.format(la, len(self.quiz)))
66         print(('of the answered questions, {} ({:.2f}) were answered correctly'
67                ).format(lc, float(lc)/la))