Skip to content

How can I import Python code into Rust? #2113

Answered by althonos
jamesray1 asked this question in Questions
Discussion options

You must be logged in to vote

Hi @jamesray1,

I think this is feasible (although not documented at all) by doing the following:

To embed the Python file within Rust:

  • use include_str! to embed your Python source into your compiled executable / library
  • use pyo3::Python.eval to add all your function definitions to the locals

To use an external Python file:

  • make sure it is in the path (possibly, edit it through py.import("sys")?.get("path"))
    (you can also simply edit sys.path within Rust to import the required Python library, but from that will work only if you have installed the Python script to a particular location)
  • use eval to define your function within the interpreter

Then you can have access to your function and…

Replies: 4 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by mejrs
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
5 participants
Converted from issue

This discussion was converted from issue #148 on January 19, 2022 12:58.