Python3 - exec()给出了if语句的语法错误

时间:2017-08-11 10:36:41

标签: python python-3.x eval interpreter

我正在创建自己的编程语言。解释器是用Python编写的。

我试图添加' if / else'命令。语法是:

if "hello" == $myString |> goto somewhere
else |> goto somewhere_else

我决定只使用Python exec()命令,而不是自己实现运算符逻辑。这就是我正在做的事情(简化):

task = task.split(' |> ', 1)  # Split on first occurence of "|> "
clause = task[0]
operation = task[1]

clauseCheck = False
clause = clause + ": clauseCheck = True" # So we can run it as python code to eval
eval(clause)  # if the clause evals to true, clauseCheck will be True

if clauseCheck:
    parse(operation)

这是我得到的错误(使用if 7 != 2 |> ...):

Traceback (most recent call last):

...

  File "interpret.py", line 139, in parse
    eval(clause)  # if the clause evals to true, clauseCheck will be True
  File "<string>", line 1
    if 7 != 2: print('True') ^ SyntaxError: invalid syntax

我已经尝试了我能想到的一切 - 我已经为eval()添加了一个换行符,无论有没有缩进,我都尝试过打印&#39;真正的&#39;而不是设置变量,我尝试使用不同的if语句。

如何让我的代码正确评估if语句?

0 个答案:

没有答案