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
On your first issue
let np = Python.import_module("numpy")
has to be called in a function that either has raises or the assignment is in atry ... 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.
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:
For more info: Mojo Docs