RustPython介绍

同CPython,Jpython,PyPy一样,RustPython,是使用Rust语言实现的Python解释器,支持Python3语法。

项目地址:https://github.com/RustPython/RustPython

RustPython真正方便的是可以编译成Wasm文件,可以直接在浏览器中使用,示例网站:https://rustpython.github.io/demo/

RustPython简单使用_github

RustPython简单使用

需要提前安装好:git、rust的cargo环境

  1. 克隆并进入项目
git clone https://github.com/RustPython/RustPython
cd RustPython
  1. 手动编译
cargo build --release --features ssl
cd target/release

启用--feaatures ssl特性可以安装pip包管理工具

编译后在target/release下生成rust_python可执行文件

  1. 使用RustPython交互解释器
$ ./rustpython 
Welcome to the magnificent Rust Python 0.4.0 interpreter 😱 🖖
No previous history.
RustPython 3.12.0
Type "help", "copyright", "credits" or "license" for more information.
>>>>>

然后你就可以在其中执行Python语句,如

>>>>> a = 1
>>>>> if a > 0:
.....     print('%d > 0' % a)
..... 
1 > 0
>>>>>

按Ctrl + Z退出交互环境
4. 执行python脚本
新建demo.py

a = 1
if a > 0:
    print('%d > 0' % a)

使用rust_python解释器执行python脚本

$ ./rustpython demo.py 
1 > 0
  1. 安装pip及三方包

安装pip

$ sudo ./rust_python --install-pip

使用pip安装三方包requests

$ ./rust_python -m pip install requests

使用三方包
新建demo2.py

import requests

r = requests.get('https://httpbin.org/get')
print(r.text)

执行脚本

$ ./rustpython demo2.py 
...省略requests包的警告信息
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.32.3", 
    "X-Amzn-Trace-Id": "Root=1-66e2c7ac-6c207dba4d8aecdd32adf668"
  }, 
  "origin": "117.186.213.150", 
  "url": "https://httpbin.org/get"
}