Search code examples
python-3.xmodulenotfounderror

`python filename.py` fails but `python3 filename.py` works on mac


I have issue with importing packages the file has just one line I.e, import numpy

So when I execute python filename.py I am getting ModuleNotFoundError whereas when I run the same with python3 filename.py it excutes without any errors.

All the versions that I have are 3.9 and above


Solution

  • As we mentioned in the comments, your default python is 3.9 and python3 as 3.11 The module error means that for one version you installed the packages, but for the other, you did not. You can figure this out with which python and which python3.

    I recommend using environments for different projects that vary in libraries or python versions.

    With venvs,create a venv with the python version installed you want.

    python3.11 -m venv myenv
    source myenv/bin/activate
    

    Sourcing it, will show you in the console (myenv) at the beginning, meaning you are in that venv. if you install packages, they will be installed in this environment.

    Similarly with anaconda:

    conda create -n mycondaenv python=3.11.6
    conda activate mycondaenv
    

    To install packages you can install them with conda or pip if those are not available:

    conda install numpy
    pip install numpy
    

    If you don't wont neither of these options, you can change the default version of python to use editing the .bashrc file:

    alias python='python3.11'
    

    And check

    source ~/.bashrc
    python --version