yglukhov / nimpy

Nim - Python bridge
MIT License
1.48k stars 60 forks source link

Import local py file #283

Closed agent10613 closed 1 year ago

agent10613 commented 1 year ago

Hi, I'm trying to import my python file into nim, via pyImport. Unfortunately, nimpy does not see this module, although both files are in the same place.

Can you please tell me what I'm doing wrong?

image C:\Users\User\User\WebstormProjects\untitled\main.nim(4) main C:\Users\User.nimble\pkgs\nimpy-0.2.0\nimpy.nim(935) pyImport C:\Users\User.nimble\pkgs\nimpy-0.2.0\nimpy\py_utils.nim(98) raisePythonError Error: unhandled exception: <class 'ModuleNotFoundError'>: No module named 'mymod' [Exception]

ctpeterson commented 1 year ago

The following seemed to resolve this issue for me (CentOS). Following the example laid out in tbuiltinpyfromnim.nim & builtinpyfromnim:

Python

import sys def hello_world(): return "hello_world"

Nim

let sys = pyImport("sys") let os = pyImport("os") discard sys.path.append(os.getcwd().to(string)) let tst {.used.} = pyImport("mymod") echo tst.hello_world()

Output

hello_world

The important thing for getting this to work on my end was importing sys in both modules & adding the local path to the Nim module with sys.

yglukhov commented 1 year ago

The only thing that should matter is python's sys.path.

import os, nimpy
discard pyImport("sys").path.append(getCurrentDir())