4

I am running a python script in Jupyter notebook and it works fine. I converted the notebook to python file and when I try to run it from the terminal I get an error saying

>>> import tensorflow as tf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tensorflow'

I have installed tensorflow and jupyter notebook using conda in a conda environment. I am on Ubuntu 18.04. I am trying to run the python script from within the environment. When I give which python I get the following output

/usr/bin/python

My limited understanding is that this is probably happening because the script is running on the base python whereas tensorflow is pointing to anaconda installation which base python cannot access. How can I run the script from the terminal?

beeprogrammer
  • 581
  • 1
  • 7
  • 18

1 Answers1

1

It looks like the script on the terminal is getting executed with a python version that is different from the one which executes in Jupyter Notebook. Since conda is being used, the issue may get resolved with following approaches:

  1. If a virtual environment is being used to run Jupyter Notebook, you can activate the virtual environment with conda activate <name> on the terminal and then run the python code.
[usr@usr]#conda activate myenv
(myenv)[usr@usr]#
  1. In case a virtual environment is not being used, the default conda python can be loaded to the PATH variable with conda activate
[usr@usr]#conda activate
(base)[usr@usr]#

In both steps 1 and 2, we can verify if tensorflow is installed in that environment with conda list command.

Alternatively, we can check what python the Jupyter Notebook uses and run the script pointing to same python in terminal.

Hope this helps.

S.Au.Ra.B.H
  • 457
  • 5
  • 9
  • Already tried approach 1. I was trying to run the python script from within the virtual environment from which I launch the jupyter notebook. From the virtual environment terminal `which python` shows `/usr/bin/python` whereas from jupyter notebook it shows `/home/thomas/anaconda3/envs/tf1p14/bin/python`. Ofcourse as you suggested, if I point to the anaconda3 environment python and run the script it works fine. – beeprogrammer Feb 03 '20 at 18:25
  • Does the `PATH` variable change when the conda environment is activated? In my machine, when I activate `myenv`, `/path/to/anaconda3/envs/myenv/bin:/path/to/anaconda3/condabin` gets added to `PATH`. – S.Au.Ra.B.H Feb 03 '20 at 18:41
  • 2
    I figured that if I follow the top solution in the question below it solves my problem https://stackoverflow.com/questions/54429210/how-do-i-prevent-conda-from-activating-the-base-environment-by-default – beeprogrammer Feb 03 '20 at 22:25