sonickun.log

備忘録

SageMathでPythonの外部ライブラリを使えるようにする

SageMathはPythonベースで作られているが、外部の(標準でない)Pythonライブラリをインポートしようとするとエラーが起きることがある。

たとえばPyCryptoだと、普通のPythonの対話シェルではインポートできているのに、

$ python
Python 2.7.11 (default, Dec  7 2016, 17:13:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from Crypto.Util.number import *
>>>

Sageでは失敗する。ということが起きる。

$ sage
┌────────────────────────────────────────────────────────────────────┐
│ SageMath version 7.3, Release Date: 2016-08-04                     │
│ Type "notebook()" for the browser-based notebook interface.        │
│ Type "help()" for help.                                            │
└────────────────────────────────────────────────────────────────────┘
sage: from Crypto.Util.number import *
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-3aca3f9edb99> in <module>()
----> 1 from Crypto.Util.number import *

ImportError: No module named Crypto.Util.number

この場合、Pythonライブラリを"Sageから"インストールする必要がある。

Solution

Sageには「シェルモード」というものがあり、そのモードでPythonライブラリのインストールコマンドを打てばよい。シェルモードはsage -shで起動する。

$ sage -sh

Starting subshell with Sage environment variables set.  Don't forget
to exit when you are done.  Beware:
 * Do not do anything with other copies of Sage on your system.
 * Do not use this for installing Sage packages using "sage -i" or for
   running "make" at Sage's root directory.  These should be done
   outside the Sage shell.

Bypassing shell configuration files...

Note: SAGE_ROOT=/path/to/sage-7.3
(sage-sh) $ pip install pycrypto
Collecting pycrypto
  Using cached pycrypto-2.6.1.tar.gz
Installing collected packages: pycrypto
  Running setup.py install for pycrypto ... done
Successfully installed pycrypto-2.6.1
(sage-sh) $ exit

これにてSage上でPyCryptoが使えるようになる。

おわり。