|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
From Nim, call PythonIt's possible to call Python code from your Nim program. It can be done with a 3rd-party library called nimpy: $ nimble install nimpy
Same output in both cases: 3.14.3 (main, Feb 13 2026, 15:31:44) [GCC 15.2.1 20260209] /usr/bin/python3 Create a custom Python moduleLet's create a custom Python module with a function and call this function from Nim. $ tree . ├── main.nim └── utils.py
def twice(n): return 2 * n
import pkg/nimpy proc main() = let utils = pyImport("utils") main() However, this drops an error: Error: unhandled exception: <class 'ModuleNotFoundError'>: No module named 'utils' [Exception] We cannot import Proof: import pkg/nimpy proc main() = let sys = pyImport("sys") path = sys.path.to(seq[string]) for p in path: echo p main() Output: /usr/lib/python314.zip /usr/lib/python3.14 /usr/lib/python3.14/lib-dynload /usr/lib/python3.14/site-packages Solution: Add the current folder to import std/os import pkg/nimpy proc main() = let sys = pyImport("sys") discard sys.path.insert(0, getAppDir()) # directory of the running binary let utils = pyImport("utils") result = utils.twice(5).to(int) echo result # 10 echo result.typeOf # int main() |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |
||||