1

我知道如何将hy模块导入 python。我所要做的就是创建一个something.hy包含hy代码的文件,然后执行以下操作...

import hy
import something
something.func('args') # assumes there is an hy function called `func`

但是,我无法弄清楚如何在 python 中评估包含hy代码的字符串。例如 ...

hycode = '(print "it works!")'
hy.SOMEHOW_EVALUATE(hycode)
# I'd like this to cause the string `it works!` to print out.

或者这个例子......

hycode = '(+ 39 3)'
result = hy.SOMEHOW_EVALUATE(hycode)
# I'd like result to now contain `42`

在 python 中使用时hy,有没有办法以这种方式评估字符串?

4

1 回答 1

3

使用hy.read_strhy.eval

>>> import hy
>>> hy.read_str("(+ 39 3)")
HyExpression([
  HySymbol('+'),
  HyInteger(39),
  HyInteger(3)])
>>> hy.eval(_)
42
>>> hycode = hy.read_str('(print "it works!")')
>>> hycode
HyExpression([
  HySymbol('print'),
  HyString('it works!')])
>>> hy.eval(hycode)
it works!

如果您从 Github master 安装 Hy,这将有效。如果你需要让它在旧版本的 Hy 上工作,你可以看到hy包中的实现__init__.py很简单

from hy.core.language import read, read_str  # NOQA
from hy.importer import hy_eval as eval  # NOQA
于 2017-09-21T20:41:51.633 回答