How can I install Python packages to a Conda environment on an Amazon SageMaker notebook instance?
3 minute read
I want to install Python packages to a specific Conda environment, check installed package versions, or create a persistent Conda environment.
Install Python packages to a specific Conda environment
If you use pip or Conda to install Python libraries on the terminal without specifying the correct Conda environment, you get a ModuleNotFoundError when importing that Python package to your running notebook. This is because you're not installing the Python packages in the correct Conda environment. To install the Python packages in the correct Conda environment, first activate the environment before running pip install or conda install from the terminal.
To run this command in a notebook cell, add an exclamation point ("!") at the beginning of the command. This forces the command to run as a shell command from the notebook and assures that the package is installed in the current Jupyter kernel.
Note: When you run conda install in a notebook cell, you can't enter an interactive response. To install packages in a notebook cell using Conda, you must explicitly pass -y. Otherwise, the command hangs and waits for user confirmation.
Sometimes, pip might fail to install some of the package's dependencies. When this happens, use Conda to install packages instead of pip. Conda verifies that all required components are satisfied before installing the packages. For more information, see Understanding Conda and Pip in the Conda documentation.
Other useful commands
To see the pre-built Conda environment, run either of the following commands in the notebook instance terminal: