如何在 python 代码中包含 Hy 代码?

How to include Hy code inside python code?

例如我们有这个 Hy 代码:

(print "Hy, world!")

我们有两段 Python 代码。第一篇:

print("Some python code")

第二部分:

print("Some other python code")

我们怎样才能做出这样的东西:

print("Some python code")
(print "Hy, world!")
print("Some other python code")

还请包括适当的导入。我还没有找到导入 Hy.

的正确方法

Per the manual:

import hy

print("Some python code")
hy.eval(hy.read_str('(print "Hy, world!")'))
print("Some other python code")

请注意,Hy 代码是在 运行 时编译的。我们可能永远无法在 Python 脚本中实现嵌入 Hy 代码,以便它可以在编译 Python 代码的同时进行编译。不过,您可以反过来将 Python 嵌入到 Hy 中:

(pys "print('Some python code')")
(print "Hy, world!")
(pys "print('Some other python code')")

您将 hy 代码放入一个单独的文件中并将其命名为 example.hy(或其他名称):

(print "Hello World")

在您的 Python-脚本中,然后您只需先导入 hy,然后再导入 example,就像您使用 Python 模块一样。

import hy
import example

之所以可行,是因为 hy 在您执行 import hy 时安装了一个导入挂钩,它允许它找到 hy 文件,编译它们,然后导入它们,就像任何其他 Python 模块。