簡體   English   中英

如何在 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的正確方法。

根據手冊:

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 模塊一樣導入它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM