Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ◇C++, ◇Clojure, ◇Scala


[ edit | logout ]
[ sandbox | passwd ]

From Nim, call Python

It's possible to call Python code from your Nim program. It can be done with a 3rd-party library called nimpy:

$ nimble install nimpy

nimpy uses the system-wide Python that was available at compile time. Let's check what is used:

Which python is used?
import sys

print(sys.version)

print(sys.executable)  # '/usr/bin/python3'
import nimpy

proc main() =
  let sys = pyImport("sys")
  echo sys.version.to(string)
  echo sys.executable.to(string)  # '/usr/bin/python3'

main()

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 module

Let's create a custom Python module with a function and call this function from Nim.

$ tree
.
├── main.nim
└── utils.py

utils.py :

def twice(n):
    return 2 * n

main.nim :

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 utils.py :( The reason is the following: Python modules are looked up in a list of directories and the current folder is not present in this list!

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 sys.path and then utils.py will be found.

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()
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 24, 17:12