skip to Main Content

why can’t i import python code in mojo

from python import Python
let np = Python.import_module("numpy")

this gives me error

/home/kali/hello.mojo:2:30: error: cannot call function that may raise in a context that cannot raise
let np = Python.import_module("numpy")
         ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
/home/kali/hello.mojo:2:30: note: try surrounding the call in a 'try' block
let np = Python.import_module("numpy")
                             ^
/home/kali/.modular/pkg/packages.modular.com_mojo/bin/mojo: error: failed to parse the provided Mojo

even in the example code of mojo in hello_interop_mojo code:

from python.python import (
    Python,
    _destroy_python,
    _init_python,
)


def main():
    print("Hello Mojo 🔥!")
    for x in range(9, 0, -3):
        print(x)
    try:
        Python.add_to_path(".")
        Python.add_to_path("./examples")
        let test_module = Python.import_module("simple_interop")
        test_module.test_interop_func()
    except e:
        print(e.value)
        print("could not find module simple_interop")

i get this error :

Hello Mojo 🔥!
9
6
3
An error occurred in Python.
could not find module simple_interop

i am running mojo on wsl ubuntu image

2

Answers


  1. On your first issue

    from python import Python
    let np = Python.import_module("numpy")
    

    let np = Python.import_module("numpy") has to be called in a function that either has raises or the assignment is in a try ... catch block. Like in this answer.

    On the second issue, you need to have simple_interop.py in the same folder where is the code you are executing.

    Login or Signup to reply.
  2. According to the Mojo docs, you need to use Python.add_to_path() to specify a path to the module that you want to import. So, the modified code would be:

    from python import Python
    
    Python.add_to_path("path/to/module")
    let np = Python.import_module("numpy")
    

    For more info: Mojo Docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search