crockeea
crockeea

Reputation: 21811

Calling Sage from Haskell

I have some sage code that I'd like to call from Haskell. The following code uses cpython to call a pure python script:

test.py:

def pytest():
    return 3.5+2

Main.hs:

import qualified CPython as Py
import qualified CPython.Protocols.Object as Py
import qualified CPython.Types as Py
import qualified CPython.Types.Module as Py
import qualified CPython.System as Py
import qualified CPython.Types.Float as Py
import qualified Data.Text as T
import GHC.IO.Handle.FD
import Data.Maybe

main :: IO ()
main = do
  Py.initialize
  path <- Py.getPath
  Py.setPath $ T.pack $ ".:" ++ T.unpack path -- path to the module to load
  test <- Py.importModule $ T.pack "test"
  uname <- Py.getAttribute test =<< (Py.toUnicode (T.pack "pytest"))
  res <- Py.callArgs uname []
  Py.print res stdout
  res' <- Py.fromFloat =<< fromJust <$> Py.cast res
  print $ (res' + 2.0 :: Double)

When I compile Main.hs and run it, I get the expected output:

5.5
7.5

If I add from sage import * to test.py, I get (once I catch the exception) ImportError("No module named 'sage'",). Of course test.py loads fine directly from sage. I expected that replacing the python executable with a symlink to the sage executable would fix the problem, but I still get the same error.

Does anyone know how to make cpython work with sage, or any other way to call a sage script from Haskell?

Upvotes: 1

Views: 313

Answers (1)

kcrisman
kcrisman

Reputation: 4402

The real question is "which" Python you are using; Sage uses its own Python, NOT your system Python. You may want to try making a link from

$ pwd; local/bin/python --version
/Users/.../Downloads/sage
Python 2.7.10
$

That is the one you will need to be linking to, in principle. In practice, you may want to read the Sage documentation about more links, or other blog posts about running scripts. But anyway it's only that Python which can use from sage import *.

Upvotes: 2

Related Questions