Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/modules/calc/calc.py

78 lines
1.8 KiB
Python
Raw Normal View History

2023-01-19 15:10:06 +00:00
from constant import consts
2023-01-20 07:50:42 +00:00
from simpleeval import EvalWithCompoundTypes, DEFAULT_FUNCTIONS, DEFAULT_NAMES, DEFAULT_OPERATORS
2023-01-19 15:10:06 +00:00
import ast
import sys
import operator as op
import math
import statistics
2023-01-20 07:50:42 +00:00
import cmath
2023-01-20 14:47:39 +00:00
import decimal
import fractions
2023-01-19 15:10:06 +00:00
funcs = {}
2023-01-20 07:50:42 +00:00
named_funcs = {}
2023-01-19 15:10:06 +00:00
def add_func(module):
2023-01-20 07:03:41 +00:00
for name in dir(module):
item = getattr(module, name)
2023-01-19 15:10:06 +00:00
if not name.startswith('_') and callable(item):
funcs[name] = item
2023-01-20 07:50:42 +00:00
def add_named_func(module):
named_funcs[module.__name__] = {}
for name in dir(module):
item = getattr(module, name)
if not name.startswith('_') and callable(item):
named_funcs[module.__name__][name] = item
2023-01-19 15:10:06 +00:00
add_func(math)
add_func(statistics)
2023-01-20 07:50:42 +00:00
add_named_func(cmath)
2023-01-20 14:47:39 +00:00
add_named_func(decimal)
add_named_func(fractions)
2023-01-19 15:10:06 +00:00
2023-01-20 07:50:42 +00:00
s_eval = EvalWithCompoundTypes(
2023-01-19 15:10:06 +00:00
operators={
**DEFAULT_OPERATORS,
ast.BitOr: op.or_,
ast.BitAnd: op.and_,
ast.BitXor: op.xor,
ast.Invert: op.invert,
},
2023-01-21 06:59:51 +00:00
functions={**funcs, **DEFAULT_FUNCTIONS,
'bin': bin,
'bool': bool,
'complex': complex,
'divmod': divmod,
'hex': hex,
'len': len,
'oct': oct,
'round': round
},
2023-01-19 15:10:06 +00:00
names={
2023-01-20 07:50:42 +00:00
**DEFAULT_NAMES, **consts, **named_funcs,
2023-01-19 15:10:06 +00:00
'pi': math.pi,
'e': math.e,
'tau': math.tau,
'inf': math.inf, 'nan': math.nan,
2023-01-20 07:50:42 +00:00
'cmath': {
'pi': cmath.pi,
'e': cmath.e,
'tau': cmath.tau,
'inf': cmath.inf,
'infj': cmath.infj,
'nan': cmath.nan,
'nanj': cmath.nanj,
**named_funcs['cmath'],
},
2023-01-19 16:45:15 +00:00
}, )
2023-01-19 15:10:06 +00:00
2023-01-19 16:45:30 +00:00
try: # rina's rina lazy solution :rina:
2023-01-20 07:43:52 +00:00
sys.stdout.write('Result ' + str(s_eval.eval(' '.join(sys.argv[1:]))))
2023-01-19 16:45:15 +00:00
except Exception as e:
2023-01-20 07:43:52 +00:00
sys.stdout.write('Failed ' + str(e))
sys.exit()