简体   繁体   中英

python3/hy - evaluating hy expressions in python?

I know how to import an hy module into python. All I have to do is create a something.hy file containing hy code and then do the following ...

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

However, I haven't been able to figure out how to evaluate a string within python which contains hy code. For example ...

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

Or this example ...

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

When using hy within python, is there any way to evaluate strings in this manner?

Use hy.read_str and hy.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!

This works if you install Hy from Github master. If you need to make it work on an old version of Hy, you can see the implementation in the hy package's __init__.py is simply

from hy.core.language import read, read_str  # NOQA
from hy.importer import hy_eval as eval  # NOQA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM