电竞比分网-中国电竞赛事及体育赛事平台

分享

RustPython 火了!將 Python 用作 Rust 腳本語言,支持 WebAssembly

 江海博覽 2024-05-09 發(fā)布于浙江

家好,很高興又見面了,我是'高級前端?進(jìn)階?',由我?guī)е蠹乙黄痍P(guān)注前端前沿、深入前端底層技術(shù),大家一起進(jìn)步,也歡迎大家關(guān)注、點贊、收藏、轉(zhuǎn)發(fā),您的支持是我不斷創(chuàng)作的動力。

RustPython 火了!將 Python 用作 Rust 腳本語言,支持 WebAssembly

什么是 RustPython

RustPython is a Python interpreter written in Rust. RustPython can be embedded into Rust programs to use Python as a scripting language for your application, or it can be compiled to WebAssembly in order to run Python in the browser. RustPython is free and open-source under the MIT license.

Python 有很多實現(xiàn),例如:

  • CPython(C),最常見的 Python 實現(xiàn)
  • Jython(Java)
  • IronPython (.NET)
  • PyPy(Python)
  • Stackless

以上 Python 實現(xiàn)都具有一些優(yōu)點:例如,Jython 將 Python 2 源代碼編譯為 Java 字節(jié)碼,然后將其路由到 Java 虛擬機(jī)。 由于 Python 代碼被轉(zhuǎn)換為 Java 字節(jié)碼,因此在運行時看起來就像一個真正的 Java 程序,因此與 Java 應(yīng)用程序集成得很好。

IronPython 與 .NET 集成良好,這意味著 IronPython 可以使用 .NET 框架和 Python 2 庫,反之亦然。

RustPython 火了!將 Python 用作 Rust 腳本語言,支持 WebAssembly

RustPython 解鎖了 Jython 和 IronPython 相同的可能性,適用于 Rust 編程語言。 此外,由于 Rust 的最小運行時間,因此能夠?qū)?RustPython 編譯為 WebAssembly,并允許用戶在瀏覽器中輕松運行 Python 代碼。

總之,RustPython 是一個用 Rust 編寫的 Python 解釋器,可以嵌入到 Rust 程序中,以使用 Python 作為應(yīng)用程序的腳本語言,也可以將其編譯為 WebAssembly 以便在瀏覽器中運行 Python。

目前 RustPython 通過 Github 通過 MIT 協(xié)議開源,有超過 18k 的 star、1.2k 的 fork、800 + 項目依賴量、代碼貢獻(xiàn)者 400+、妥妥的優(yōu)質(zhì)開源項目。

如何使用 RustPython

RustPython 需要安裝 Rust 最新的穩(wěn)定版本,如果系統(tǒng)上當(dāng)前尚未安裝 Rust,可以按照 rustup.rs 中的說明進(jìn)行安裝。

要檢查當(dāng)前運行的 Rust 版本,請使用 rustc --version。 如果想更新,rustup update stable 會將 Rust 安裝更新到最新的穩(wěn)定版本。

要在本地構(gòu)建 RustPython,首先克隆源代碼:

git clone https://github.com/RustPython/RustPython

然后切換到 RustPython 目錄并運行 Demo(注意:需要 --release 來防止 Windows 上的堆棧溢出):

// 切換到指定目錄運行
$ cd RustPython
$ cargo run --release demo_closures.py
Hello, RustPython!

或者使用交互式 Shell 命令:

// 使用交互式 shell $ cargo run --release Welcome to rustpython >>>>> 2+2 4

還可以使用以下命令安裝并運行 RustPython:

// cargo 安裝
$ cargo install --git https://github.com/RustPython/RustPython
$ rustpython
Welcome to the magnificent Rust Python interpreter
>>>>>

最后值得一提的是,RustPython 有一個非常實驗性的 JIT 編譯器,可以將 python 函數(shù)編譯為本機(jī)代碼,但是需要手動啟用:

// 要安裝 autoconf、automake、libtool 和 clang cargo run --features jit

此時,如果要編譯函數(shù),可以對其調(diào)用 jit() 即可:

def foo():
    a = 5
    return 10 + a

foo.__jit__()  
// 將 foo 編譯為本機(jī)代碼,后續(xù)調(diào)用將執(zhí)行本機(jī)代碼
assert foo() == 15

更多關(guān)于 RustPython 的用法和示例可以參考文末資料,本文不再過多展開。

參考資料

https://github.com/RustPython/RustPython

https://rustpython./

https://www./rust-vs-python/

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多