Created
January 13, 2026 07:11
-
-
Save pythonhacker/6c6f842ff9590463b69c01e610eeb63d to your computer and use it in GitHub Desktop.
A Python cmd.Cmd console supporting arithmetic operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import cmd | |
| import shlex | |
| import operator | |
| from functools import reduce | |
| class CalcConsole(cmd.Cmd): | |
| """ A console that helps to perform regular arithmetic """ | |
| prompt = "Calc> " | |
| def _parse(self, line): | |
| """ Parse an input line and return items """ | |
| items = shlex.split(line) | |
| try: | |
| try: | |
| # Try pure int first | |
| nums = [int(i) for i in items] | |
| except: | |
| # Fallback to float | |
| nums = [float(i) for i in items] | |
| except Exception as ex: | |
| print(f"error parsing arguments - {ex}") | |
| return [] | |
| return nums | |
| def do_add(self, arg): | |
| """ Implement addition """ | |
| nums = self._parse(arg) | |
| print(sum(nums)) | |
| def do_prod(self, arg): | |
| """ Implement multiplication """ | |
| nums = self._parse(arg) | |
| print(reduce(operator.mul, nums)) | |
| def do_div(self, arg): | |
| """ Implement division """ | |
| # Only allow two operators | |
| items = self._parse(arg) | |
| if len(items) != 2: | |
| print('usage: div <dividend> <divisor>') | |
| return | |
| if items[1] == 0: | |
| print('division by zero not allowed') | |
| return | |
| print(items[0]/items[1]) | |
| def default(self, arg): | |
| """ Allow console generic arithmetic using eval """ | |
| try: | |
| print(eval(arg)) | |
| except Exception as ex: | |
| print(f"error evaluating {arg} : {ex}") | |
| def do_EOF(self, line): | |
| return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment