I'm automating our daily stuff .Here my code takes absolute path of a directory as input. It read each file in the directory which is sorted by file name. and then it Concatenate the content of each file to form a string.The final concatenated string needs to get validated. If string is valid it will yield true else false if it is invalid expression.I'm thinking valid expression : "( a+ b ) * c + (d /e )', I Invalid expression : "( a + b ".
This is below code that was being used to do the stuff.
from math import *
import os
import glob
Path = os.path.abspath("mydir/myfile.txt")
files = glob.glob(Path)
for name in files:
try:
with open(name) as f:
s+=f.read()
sys.stdout.write(s)
except IOError as exec:
if exc.errno != errno.EISDIR:
raise
def validateSyntax(a):
functions = {'__builtins__': None}
variables = {'__builtins__': None}
functions = {'acos': acos,
'asin': asin,
'atan': atan,
'atan2': atan2,
'ceil': ceil,
'cos': cos,
'cosh': cosh,
'degrees': degrees,
'exp': exp,
'fabs':fabs,
'floor': floor,
'fmod': fmod,
'frexp': frexp,
'hypot': hypot,
'ldexp': ldexp,
'log': log,
'log10': log10,
'modf': modf,
'pow': pow,
'radians': radians,
'sin': sin,
'sinh': sinh,
'sqrt': sqrt,
'tan': tan,
'tanh': tanh}
variables = {'e': e, 'pi': pi}
try:
eval(s,variables, functions)
except (SyntaxError, NameError, ZeroDivisionError):
return False
else:
pass