Trouble importing modules in Python with "ModuleNotFoundError"

Hi all,

I’m trying to run a Python script that uses certain modules, but I keep getting the following error:

ModuleNotFoundError: No module named 'module_name'

I’ve already tried installing the modules using the pip install command in my terminal or command prompt, and it says “requirement already satisfied”, but I’m still getting the error. That happened for numpy, scipy, and a few others.

I’m running Python version 3.10.4 on Windows.

Can anyone help me figure out why I’m getting this error and how I can fix it?

Thanks in advance!

Judging by the error, it looks like you’re attempting to import the string “module_name”, rather than the actual name of the module.

How are you going about your importations, if I may ask?

Oh, I apologize, I put “module_name” here to indicate that this happens for more than one module (like numpy and scipy). I’m sorry, I didn’t quite get your question. What do you mean by how am I going about my importations?

Aaaah, I see! That makes sense! Fair enough!

I mean, could you show us the code that you’re using? Is it just “import numpy” and so on, or are you doing some sort of dynamic importation, or something else…?

Yeah sure! Here’s the code:

from direct.showbase.ShowBase import ShowBase
from scipy.spatial import Voronoi, voronoi_plot_2d
import numpy as np

class VoronoiApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        # generate random points
        np.random.seed(0)
        points = np.random.rand(20, 2)

        # construct Voronoi diagram
        vor = Voronoi(points)

        # create Panda3D nodes for the Voronoi diagram
        diagram = voronoi_plot_2d(vor, show_vertices=False, line_colors=[1, 1, 1, 1])
        node = self.aspect2d.attach_new_node(diagram)
        node.set_scale(2)
        node.set_pos(-1, 0, -1)

app = VoronoiApp()
app.run()

For this code, it says “ModuleNotFoundError: No module named ‘scipy’”, even though when I try to do the following command

pip install scipy

it says it’s already installed. Any idea what it could be?

Hmm… Well, the importation looks to be standard.

Two guesses then come to mind:

First, that the problem might be one of paths: your environment isn’t set up such that Python can easily find the module in question, while other modules are more-easily found.

And second, that pip is being run via a different version of Python than Panda uses. (For example: I think that my own system’s default Python installation is a version of Python 2, while Panda uses Python 3. Thus when I run pip, I usually do so via an explicit call to Python 3.)

For the first, I’m not sure offhand of how to check your paths; another may be able to help you there.

For the second, however, you could try running pip as follows and seeing whether it helps:

python3 -m pip <whatever commands you want here>