【问题标题】:python3/hy - evaluating hy expressions in python?python3/hy - 在 python 中评估 hy 表达式?
【发布时间】:2017-09-21 18:36:54
【问题描述】:

我知道如何将hy 模块导入python。我所要做的就是创建一个包含hy 代码的something.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 时,有没有办法以这种方式评估字符串?

【问题讨论】:

    标签: python python-3.x eval hy


    【解决方案1】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多