/
op
executable file
·56 lines (42 loc) · 1003 Bytes
/
op
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/python
# Command line calculator.
#
# Create links to 'op'
# ln -s op add
# ln -s op sub
# ln -s op mul
# ln -s op div
#
#
# davep ??-2011
import sys
import os
import operator
def mknum( string ) :
"""Try converting a string to base-10 integer. If that fails, try base-16.
If that fails, we'll allow the ValueError to propogate."""
value = None
# try float first so things like 'div 1024 3' will give a float answer
try :
value = float(string)
return value
except ValueError:
pass
try :
value = int(string,10)
return value
except ValueError:
pass
# ok, last chance; maybe it's hex
value = int(string,16)
return value
exename = os.path.basename(sys.argv[0])
opmap = {
"add" : operator.add,
"sub" : operator.sub,
"mul" : operator.mul,
"div" : operator.div,
}
if exename not in opmap :
sys.exit(1)
print reduce( opmap[exename], [ mknum(s) for s in sys.argv[1:] ] )