Skip to content

Instantly share code, notes, and snippets.

@beejjorgensen
Last active October 11, 2022 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beejjorgensen/a495235b2e6a917c22a1e5a518e3bd96 to your computer and use it in GitHub Desktop.
Save beejjorgensen/a495235b2e6a917c22a1e5a518e3bd96 to your computer and use it in GitHub Desktop.
A simple command line calculator, wrapper around Python
#!/usr/bin/env python
#
# A command line calculator
#
# Just a wrapper around Python
#
# Put the expression in single quotes if it contains special shell
# characters.
#
# Examples:
#
# % c 2 + 0x23-0b11
# 34 0x22 0b100010
#
# % c '2**16 - 2048'
# 63488 0xf800 0b1111100000000000
#
import sys
expression = " ".join(sys.argv[1:])
if expression == '':
print("usage: c 'expression'", file=sys.stderr)
sys.exit(1)
from math import *
try:
result = eval(f"'\t'.join((str({expression}), hex({expression}), bin({expression})))")
except TypeError:
result = eval(str(expression))
except SyntaxError:
print(f"c: invalid expression: {expression}", file=sys.stderr)
sys.exit(1)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment