4

I'm writing Sage scripts with the aid of the Jupyter notebook. It's all fine until I try to import regular Python packages/libraries, things I installed with pip or otherwise and sit under /usr/local/lib/python3.8/dist-packages/. Say, CoolProp, a fluid property package. When I try:

import CoolProp.CoolProp as CP

I get this error:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-2-b88e3e84ef2b> in <module>
----> 1 import CoolProp.CoolProp as CP

ModuleNotFoundError: No module named 'CoolProp'

I assume I should provide the path to CoolProp somehow, but how to do this within a script? I have Sage installed under ~/sage-9.3.

Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27

1 Answers1

5

Installing Python packages for Sage

The packages should be installed for Sage's Python, which, depending on how you installed Sage, might not be your system Python.

If sage is in your PATH, try this in a terminal:

sage --pip install CoolProp

Otherwise, use the full path:

~/sage-9.3/sage --pip install CoolProp

Alternatively, at the Sage prompt (or in a Jupyter notebook running the Sage kernel), run:

%pip install CoolProp

After that, the import should work.

Duplicate copies of packages

One way to avoid keeping duplicate copies of packages is to always use Sage's Python.

It can be started by running sage --python or ~/sage-9.3/local/bin/python.

Other possibilities include using an alias:

alias python='sage --python'

or

alias python='~/sage-9.3/local/bin/python'

or tweaking your PATH shell variable:

PATH=~/sage-9.3/local/bin:$PATH

The line defining the alias or setting the PATH could be added to your shell settings file (which could be .bashrc or .bash_profile or .zshrc or similar).

Better, add a symlink to Sage's Python to some location that is earlier in your PATH than your system Python:

ln -s ~/sage-9.3/local/bin:$PATH /usr/local/bin

or, if that gives a permission error,

sudo ln -s ~/sage-9.3/local/bin:$PATH /usr/local/bin

The advantage is this command can be run once and for all, with no need to change your shell settings file.

In all cases, running python will run Sage's Python.

To stop using Sage's Python as your main Python, either delete the line defining an alias or tweaking your PATH from your shell settings file, or remove the symlink if you used that solution:

rm /usr/local/bin/python

or, if that gives a permission error,

sudo rm /usr/local/bin/python

Dedicated environments

One modern trend is to use dedicated environments for each project you work on, with a description of that environment stored in a text file.

This can be done with Python's venv or with Conda.

Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27