简体   繁体   English

import tensorflow 可以在 jupyter notebook 中使用,但不能在命令行中使用。 使用 conda 安装 tensorflow 和 jupyter notebook

[英]import tensorflow works in jupyter notebook but not from command line. Using conda to install tensorflow and jupyter notebook

I am running a python script in Jupyter notebook and it works fine.我在 Jupyter 笔记本中运行一个 python 脚本,它工作正常。 I converted the notebook to python file and when I try to run it from the terminal I get an error saying我将笔记本转换为 python 文件,当我尝试从终端运行它时,我收到一条错误消息

>>> 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.我已经在 conda 环境中使用 conda 安装了 tensorflow 和 jupyter notebook。 I am on Ubuntu 18.04.我在 Ubuntu 18.04 上。 I am trying to run the python script from within the environment.我正在尝试从环境中运行 python 脚本。 When I give which python I get the following output当我给出which python我得到以下输出

/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.我有限的理解是,这可能是因为脚本在基础 python 上运行,而 tensorflow 指向基础 python 无法访问的 anaconda 安装。 How can I run the script from the terminal?如何从终端运行脚本?

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.看起来终端上的脚本正在使用与在 Jupyter Notebook 中执行的版本不同的 Python 版本执行。 Since conda is being used, the issue may get resolved with following approaches:由于正在使用conda ,因此可以通过以下方法解决该问题:

  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.如果使用虚拟环境运行 Jupyter Notebook,您可以在终端使用conda activate <name>激活虚拟环境,然后运行 ​​python 代码。
[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如果没有使用虚拟环境,可以使用conda activate将默认的 conda python 加载到PATH变量
[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.在第 1 步和第 2 步中,我们可以使用 conda conda list命令验证该环境中是否安装了 tensorflow。

Alternatively, we can check what python the Jupyter Notebook uses and run the script pointing to same python in terminal.或者,我们可以检查Jupyter Notebook 使用的python 并在终端中运行指向相同 python 的脚本。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM