0

I'm trying to import tensorflow as ts in my script. While everything is fine in a Notebook, when I try to recreate the same script in a .py file the import returns the following, popular message:

ModuleNotFoundError: No module named 'tensorflow'

Note that both Jupyter and terminal are using the same virtual environment. In Notebook it's picked as a Kernel and in terminal it's activated with conda.

I was convinced the whole Kernel/env idea was about preventing exactly that kind of situations. Although I'm new to python so maybe I'm missing something basic.

Also, this might have something to do with that I'm using an M1 and macos, so I have the tensorflow-macos installed. But please consider there might be other reasons.

wiktus239
  • 1,404
  • 2
  • 13
  • 29
  • I'm doubtful "both Jupyter and terminal are using the same virtual environment" given your experience. Does your script work if you place your script in the same directory as your notebook that works and from inside the notebook use `%run my_script.py` (where you replace `my_script.py` with your script name)? If that fails, in the notebook, try `%run -i my_script.py` or `%run -m my_script.py`. I cannot tell you why it's happening but the environment idea and linking the kernel to it should indeed be preventing it. – Wayne Jul 21 '22 at 18:19
  • 1
    @Wayne thanks for the suggestion! However, it is indeed the same environment. Problem was caused by a previous `pyenv` installation, which I no longer need – wiktus239 Jul 22 '22 at 09:57

1 Answers1

1

Make sure your pyenv installation doesn't interfere with the conda environments. Pyenv can overrule which python installation is used even if the conda environment has picked another. In my case it was the reason. Jupyter Notebook wasn't affected by pyenv. There are two solutions:

  1. Remove pyenv
  2. Make sure it is clear to you how both pyenv and conda are affecting your setup and correct it. Some considerations and suggestions are mentioned in this question: Installing anaconda with pyenv, unable to configure virtual environment
wiktus239
  • 1,404
  • 2
  • 13
  • 29