inline_python: 在rust中编写python

准备

这个库需要nightly版本的rust,因此需要切换到nightly

rustup toolchain install nightly # 下载nightly版本
rustup override set nightly # 临时切换
rustup default nightly # 将默认版本设置为nightly

依赖

[dependencies]
inline-python = "0.10.0"

代码编写

use inline_python::python;

fn main() {
    let who = "world";
    let n = 5;
    python! {
        for i in range('n):
            print(i, "Hello", 'who)
        print("Goodbye")
    }
}

conda

如果使用conda则可能遇到环境变量PYTHONHOME缺失的问题,报错如下

Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = (not set)
  program name = 'python'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'D:\\Rust\\.rustup\\toolchains\\nightly-x86_64-pc-windows-msvc\\bin\\rustc.exe'
  sys.base_prefix = 'D:\\anaconda3'
  sys.base_exec_prefix = 'D:\\anaconda3'
  sys.platlibdir = 'lib'
  sys.executable = 'D:\\Rust\\.rustup\\toolchains\\nightly-x86_64-pc-windows-msvc\\bin\\rustc.exe'
  sys.prefix = 'D:\\anaconda3'
  sys.exec_prefix = 'D:\\anaconda3'
  sys.path = [
    'D:\\anaconda3\\python39.zip',
    '.\\DLLs',
    '.\\lib',
    'D:\\Rust\\.rustup\\toolchains\\nightly-x86_64-pc-windows-msvc\\bin',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000045e8 (most recent call first):
<no Python frame>
error: could not compile `py-demo`

此时找到conda环境中python所在目录设置为PYTHONHOME即可

参考

inline-python - crates.io: Rust Package Registry

Writing Python inside your Rust code — Part 1 - Mara's Blog (m-ou.se)

posted @ 2022-10-17 13:36  七つ一旋桜  阅读(97)  评论(0)    收藏  举报