从JSON数据解释Python函数

时间:2019-05-01 04:52:20

标签: python json sympy

我试图确定通过json传递给python的两个简单函数的等效性,如下所示:

PHP:

$data = array("2*x", "x*2");
$result = shell_exec('python /path/check.py ' . escapeshellarg(json_encode($data)));

Python:

import sys, json
from sympy import *

try:
    data = json.loads(sys.argv[1])
except:
    sys.exit(1)

x = Symbol('x')

response = data[0]
answer = data[1]

result = response==answer

print json.dumps(result)

我的假设是结果返回false,因为响应和答案被解释为字符串。我如何比较这两个函数,就像我在python中那样设置变量一样:

response = 2*x
answer = x*2

1 个答案:

答案 0 :(得分:1)

您需要将字符串转换为SymPy表达式:

sympify(answer) == sympify(response)