I am currently creating a programming language for beginners. My plan is to append all of the user's input to a python file out.py
, and I will convert the then I plan to run that file and show the output.
The problem I am having is when I add the line to out.write(equation)
, it only writes to the file when the program ends. I also have the same problems on the first lines where I append the functions file. Essentially, the file only gets written to when the program wins.
Python file with code:
# Open the file that we will write all of the lines of code to
out = open("out.py","w")
# Open the file with all of the built in functions
functions = open("functions.py","r").read()
# Add built in functions to out so that the user can use them
out.write(functions)
out.write("\n")
operators = ['+', '-', '*', '/']
var_assign = '='
variables = {}
# Lexer
def lex(line):
idx = 0
line = line.replace(" ", "")
num = ""
tok = ""
isNum = False
tokens = []
for char in line:
if char.isdigit():
isNum = True
num+=char
elif char in operators:
if isNum:
tokens.append(f"NUM:{num}")
num=""
isNum = False
tokens.append(f"OP:{char}")
elif char == "=":
try:
if line[:idx].isdigit():
return None
else:
tokens.append(f"VAR_ASSIGN:{line[:idx]}={line[idx+1:]}")
except:
return ""
elif char.isalpha() and "=" not in line:
try:
if '-' in line or '+' in line or '*' in line or '/' in line:
tokens.append(f"VAR_USE:{char}")
else:
tokens.append(f"VAR_CALL:{line}")
except:
return ""
idx+=1
if isNum:
tokens.append(f"NUM:{num}")
return tokens
# Parser
def parse(tokens):
equation = ""
if not tokens:
return "Syntax error"
for tok in tokens:
if "NUM" in tok:
equation+=tok[4:]
elif "OP" in tok:
equation+=tok[3:]
elif "VAR_ASSIGN" in tok:
tok = tok[11:]
variables[tok[:tok.index('=')]] = tok[tok.index('=')+1:]
return variables[tok[:tok.index('=')]]
elif "VAR_CALL" in tok:
try:
return variables[tok[9:]]
except:
return "Variable not defined"
elif "VAR_USE" in tok:
try:
equation += variables[tok[8:]]
except:
return "Variable not defined"
try:
out.write(equation)
out.write("\n")
return eval(equation)
except:
return f"Invalid equation {equation}"
while True:
data = input("KPP>")
print(parse(lex(data)))
Output file with the input of 1+2, after I end the file
def show(arg):
print(arg)
1+2