I'm trying to run Astropy under Windows 7 CPython 2.7.5.
I had a fresh install from the binary available at the PyPi but when I try to import I got a SystemError: Parent module 'astropy' not loaded, cannot perform relative import
However, if I try to import it again, the error changes to a ImportError that is a known issue related to system permissions Astropy Known Issues
The problem is I installed everything system-wide using a admin account. Any suggestions on how to proceed?
Here you can see the full trackback.
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information.
IPython 1.1.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. Using matplotlib backend: TkAgg
In [1]: import astropy Custom TB Handler failed, unregistering
--------------------------------------------------------------------------- SystemError Traceback (most recent call last) c:\python27\lib\site-packages\astropy\logger.py in ipy_exc_handler(ipyshell, ety pe, evalue, tb, tb_offset)
270 def ipy_exc_handler(ipyshell, etype, evalue, tb, tb_offset=N one):
271 # First use our excepthook
--> 272 self._excepthook(etype, evalue, tb)
273
274 # Now also do IPython's traceback
c:\python27\lib\site-packages\astropy\logger.py in _excepthook(self, etype, valu e, traceback)
220 self.error(message, extra={'origin': mod.__name__})
221 else:
--> 222 self.error(message)
223 self._excepthook_orig(etype, value, traceback)
224
C:\Python27\lib\logging\__init__.pyc in error(self, msg, *args,
**kwargs) 1173 """ 1174 if self.isEnabledFor(ERROR):
-> 1175 self._log(ERROR, msg, args, **kwargs) 1176 1177 def exception(self, msg, *args, **kwargs):
C:\Python27\lib\logging\__init__.pyc in _log(self, level, msg, args, exc_info, e xtra) 1266 exc_info = sys.exc_info() 1267 record = self.makeRecord(self.name, level, fn, lno, msg, args, e xc_info, func, extra)
-> 1268 self.handle(record) 1269 1270 def handle(self, record):
C:\Python27\lib\logging\__init__.pyc in handle(self, record) 1276 """ 1277 if (not self.disabled) and self.filter(record):
-> 1278 self.callHandlers(record) 1279 1280 def addHandler(self, hdlr):
C:\Python27\lib\logging\__init__.pyc in callHandlers(self, record) 1316 found = found + 1 1317 if record.levelno >= hdlr.level:
-> 1318 hdlr.handle(record) 1319 if not c.propagate: 1320 c = None #break out
C:\Python27\lib\logging\__init__.pyc in handle(self, record)
747 self.acquire()
748 try:
--> 749 self.emit(record)
750 finally:
751 self.release()
c:\python27\lib\site-packages\astropy\logger.py in
_stream_formatter(self, recor d)
337 color_print(record.levelname, 'brown', end='')
338 else:
--> 339 color_print(record.levelname, 'red', end='')
340 print(": {0} [{1:s}]".format(record.msg, record.origin))
341
c:\python27\lib\site-packages\astropy\utils\console.py in color_print(*args, **k wargs)
228
229 write = file.write
--> 230 if isatty(file) and USE_COLOR():
231 for i in xrange(0, len(args), 2):
232 msg = args[i]
c:\python27\lib\site-packages\astropy\config\configuration.py in
__call__(self)
334
335 #get the value from the relevant `configobj.ConfigObj` object
--> 336 sec = get_config(self.module)
337 if self.name not in sec:
338 self.set(self.defaultvalue)
c:\python27\lib\site-packages\astropy\config\configuration.py in get_config(pack ageormod, reload)
400
401 from .paths import get_config_dir
--> 402 from ..utils import find_current_module
403
404 if packageormod is None:
SystemError: Parent module 'astropy' not loaded, cannot perform relative import The original exception:
In [2]: import astropy
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-2-d192094ef7da> in <module>()
----> 1 import astropy
c:\python27\lib\site-packages\astropy\__init__.py in <module>()
125 if not _ASTROPY_SETUP_:
126 from .logger import _init_log
--> 127 from . import config
128
129 import os
ImportError: cannot import name config
In [3]:
More info:
This is a similar problem to the described here, but I don't want to use Canopy or Anaconda.
Related
I want to use ggplot2 within Jupyter Notebook. However, when I try to make an R magic cell and introduce a variable, I get an error.
Here is the code (one paragraph indicates one cell):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import rpy2
%matplotlib inline
from rpy2.robjects import pandas2ri
pandas2ri.activate()
%load_ext rpy2.ipython
%%R
library(ggplot2)
data = pd.read_csv('train_titanic.csv')
%%R -i data -w 900 -h 480 -u px
With this last cell, I get the following error (incl traceback):
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/pandas2ri.py in py2rpy_pandasdataframe(obj)
54 try:
---> 55 od[name] = conversion.py2rpy(values)
56 except Exception as e:
~/anaconda3/envs/catenv/lib/python3.7/functools.py in wrapper(*args, **kw)
839
--> 840 return dispatch(args[0].__class__)(*args, **kw)
841
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/pandas2ri.py in py2rpy_pandasseries(obj)
125 if type(x) is not homogeneous_type:
--> 126 raise ValueError('Series can only be of one type, or None.')
127 # TODO: Could this be merged with obj.type.name == 'O' case above ?
ValueError: Series can only be of one type, or None.
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in from_object(cls, obj)
367 try:
--> 368 mv = memoryview(obj)
369 res = cls.from_memoryview(mv)
TypeError: memoryview: a bytes-like object is required, not 'Series'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-14-75e210679e4a> in <module>
----> 1 get_ipython().run_cell_magic('R', '-i data -w 900 -h 480 -u px', '\n\n')
~/anaconda3/envs/catenv/lib/python3.7/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2360 with self.builtin_trap:
2361 args = (magic_arg_s, cell)
-> 2362 result = fn(*args, **kwargs)
2363 return result
2364
</home/morgan/anaconda3/envs/catenv/lib/python3.7/site-packages/decorator.py:decorator-gen-130> in R(self, line, cell, local_ns)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/ipython/rmagic.py in R(self, line, cell, local_ns)
721 raise NameError("name '%s' is not defined" % input)
722 with localconverter(converter) as cv:
--> 723 ro.r.assign(input, val)
724
725 tmpd = self.setup_graphics(args)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
190 kwargs[r_k] = v
191 return (super(SignatureTranslatedFunction, self)
--> 192 .__call__(*args, **kwargs))
193
194
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
111
112 def __call__(self, *args, **kwargs):
--> 113 new_args = [conversion.py2rpy(a) for a in args]
114 new_kwargs = {}
115 for k, v in kwargs.items():
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/functions.py in <listcomp>(.0)
111
112 def __call__(self, *args, **kwargs):
--> 113 new_args = [conversion.py2rpy(a) for a in args]
114 new_kwargs = {}
115 for k, v in kwargs.items():
~/anaconda3/envs/catenv/lib/python3.7/functools.py in wrapper(*args, **kw)
838 '1 positional argument')
839
--> 840 return dispatch(args[0].__class__)(*args, **kw)
841
842 funcname = getattr(func, '__name__', 'singledispatch function')
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/pandas2ri.py in py2rpy_pandasdataframe(obj)
59 'The error is: %s'
60 % (name, str(e)))
---> 61 od[name] = StrVector(values)
62
63 return DataFrame(od)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/robjects/vectors.py in __init__(self, obj)
382
383 def __init__(self, obj):
--> 384 super().__init__(obj)
385 self._add_rops()
386
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in __init__(self, obj)
286 super().__init__(obj)
287 elif isinstance(obj, collections.abc.Sized):
--> 288 super().__init__(type(self).from_object(obj).__sexp__)
289 else:
290 raise TypeError('The constructor must be called '
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in from_object(cls, obj)
370 except (TypeError, ValueError):
371 try:
--> 372 res = cls.from_iterable(obj)
373 except ValueError:
374 msg = ('The class methods from_memoryview() and '
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/conversion.py in _(*args, **kwargs)
26 def _cdata_res_to_rinterface(function):
27 def _(*args, **kwargs):
---> 28 cdata = function(*args, **kwargs)
29 # TODO: test cdata is of the expected CType
30 return _cdata_to_rinterface(cdata)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in from_iterable(cls, iterable, populate_func)
317 if populate_func is None:
318 cls._populate_r_vector(iterable,
--> 319 r_vector)
320 else:
321 populate_func(iterable, r_vector)
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in _populate_r_vector(cls, iterable, r_vector)
300 r_vector,
301 cls._R_SET_VECTOR_ELT,
--> 302 cls._CAST_IN)
303
304 #classmethod
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in _populate_r_vector(iterable, r_vector, set_elt, cast_value)
237 def _populate_r_vector(iterable, r_vector, set_elt, cast_value):
238 for i, v in enumerate(iterable):
--> 239 set_elt(r_vector, i, cast_value(v))
240
241
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/sexp.py in _as_charsxp_cdata(x)
430 return x.__sexp__._cdata
431 else:
--> 432 return conversion._str_to_charsxp(x)
433
434
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/conversion.py in _str_to_charsxp(val)
118 s = rlib.R_NaString
119 else:
--> 120 cchar = _str_to_cchar(val)
121 s = rlib.Rf_mkCharCE(cchar, _CE_UTF8)
122 return s
~/anaconda3/envs/catenv/lib/python3.7/site-packages/rpy2/rinterface_lib/conversion.py in _str_to_cchar(s, encoding)
97 def _str_to_cchar(s, encoding: str = 'utf-8'):
98 # TODO: use isStrinb and installTrChar
---> 99 b = s.encode(encoding)
100 return ffi.new('char[]', b)
101
AttributeError: 'float' object has no attribute 'encode'
So I find that it is not possible to even start an R magic cell while importing my pandas dataframe object. However, I have tried creating R vectors inside the cell, and find I can plot these using ggplot2 with no issues.
I am using Python 3.7.6, rpy2 3.1.0, jupyter-notebook 6.0.3and am using Ubuntu 18.04.2 LTS on Windows Subsystem for Linux.
The problem is most likely with one (or more) columns having more than one type - therefore it is impossible to transfer the data into an R vector (which can hold only one data type). The traceback may be overwhelming, but here is the relevant part:
ValueError: Series can only be of one type, or None.
Which column it is? Difficult to say without looking at the dataset that you load, but my general solution is to check the types in the columns:
types = data.applymap(type).apply(set)
types[types.apply(len) > 1]
Anything returned by the snippet above would be a candidate culprit. There are many different ways of dealing with the problem, depending on the exact nature of the data. Workarounds that I frequently use include:
calling data = data.infer_objects() - helps if the pandas did not catch up with a dtype change and still stores the data with (suboptimal) Python objects
filling NaN with an empty string or a string constant if you have missing values in a string column (e.g. str_columns = str_columns.fillna(''))
dates.apply(pd.to_datetime, axis=1) if you have datetime objects but the dtype is object
using df.applymap(lambda x: datetime.combine(x, datetime.min.time()) if not isinstance(x, datetime) else x) if you have a mixture of date and datetime objects
In some vary rare cases pandas stores the data differently than expected by rpy2 (following certain manipulations); then writing the dataframe down to a csv file and reading it from the disk again helps - but this is likely not what you are facing here, as you start from a newly read dataframe.
I just noticed there might be an even simpler reason for the problem. For some reason, pandas2ri requires you to call pandas2ri.activate()after importing it. This solved the problem for me.
I tried to install matplotlib on Windows 10 Bash shell.
After that, I ran following lines:
$ ipython3
then
In[1]: %pylab
then it gives me a following error:
---------------------------------------------------------------------------
TclError Traceback (most recent call last)
<ipython-input-1-4ab7ec3413a5> in <module>()
----> 1 get_ipython().magic('pylab')
/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2164 magic_name, _, magic_arg_s = arg_s.partition(' ')
2165 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2166 return self.run_line_magic(magic_name, magic_arg_s)
2167
2168 #-------------------------------------------------------------------------
/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2085 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2086 with self.builtin_trap:
-> 2087 result = fn(*args,**kwargs)
2088 return result
2089
/usr/lib/python3/dist-packages/IPython/core/magics/pylab.py in pylab(self, line)
/usr/lib/python3/dist-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
190 # but it's overkill for just that one bit of state.
191 def magic_deco(arg):
--> 192 call = lambda f, *a, **k: f(*a, **k)
193
194 if isinstance(arg, collections.Callable):
/usr/lib/python3/dist-packages/IPython/core/magics/pylab.py in pylab(self, line)
129 import_all = not args.no_import_all
130
--> 131 gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
132 self._show_matplotlib_backend(args.gui, backend)
133 print ("Populating the interactive namespace from numpy and matplotlib")
/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in enable_pylab(self, gui, import_all, welcome_message)
2918 from IPython.core.pylabtools import import_pylab
2919
-> 2920 gui, backend = self.enable_matplotlib(gui)
2921
2922 # We want to prevent the loading of pylab to pollute the user's
/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui)
2879 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2880
-> 2881 pt.activate_matplotlib(backend)
2882 pt.configure_inline_support(self, backend)
2883
/usr/lib/python3/dist-packages/IPython/core/pylabtools.py in activate_matplotlib(backend)
244 matplotlib.rcParams['backend'] = backend
245
--> 246 import matplotlib.pyplot
247 matplotlib.pyplot.switch_backend(backend)
248
/usr/local/lib/python3.4/dist-packages/matplotlib/pyplot.py in <module>()
2510 # are no-ops and the registered function respect `mpl.is_interactive()`
2511 # to determine if they should trigger a draw.
-> 2512 install_repl_displayhook()
2513
2514 ################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
/usr/local/lib/python3.4/dist-packages/matplotlib/pyplot.py in install_repl_displayhook()
163 ipython_gui_name = backend2gui.get(get_backend())
164 if ipython_gui_name:
--> 165 ip.enable_gui(ipython_gui_name)
166 else:
167 _INSTALL_FIG_OBSERVER = True
/usr/lib/python3/dist-packages/IPython/terminal/interactiveshell.py in enable_gui(gui, app)
306 from IPython.lib.inputhook import enable_gui as real_enable_gui
307 try:
--> 308 return real_enable_gui(gui, app)
309 except ValueError as e:
310 raise UsageError("%s" % e)
/usr/lib/python3/dist-packages/IPython/lib/inputhook.py in enable_gui(gui, app)
526 e = "Invalid GUI request %r, valid ones are:%s" % (gui, list(guis.keys()))
527 raise ValueError(e)
--> 528 return gui_hook(app)
529
/usr/lib/python3/dist-packages/IPython/lib/inputhook.py in enable_tk(self, app)
322 if app is None:
323 import tkinter
--> 324 app = tkinter.Tk()
325 app.withdraw()
326 self._apps[GUI_TK] = app
/usr/lib/python3.4/tkinter/__init__.py in __init__(self, screenName, baseName, className, useTk, sync, use)
1852 baseName = baseName + ext
1853 interactive = 0
-> 1854 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
1855 if useTk:
1856 self._loadtk()
TclError: no display name and no $DISPLAY environment variable
I'd appreciate if anybody can point out how to remove this error. Thank you.
There is no official display environment for bash on Windows.
You need to install unoffical display environment, i.e. xming (https://sourceforge.net/projects/xming/)
After installing xming you need to export as DISPLAY=:0.
You also need to install qtconsole. sudo apt-get install qtconsole
However, I don't suggest going in this way, there is a much easier way for using ipython on Windows. You can install Anaconda on Windows and you can use ipython without any problems like this (https://www.continuum.io/downloads)
I am getting NameError: name 'unicode' is not defined when using yHat's ggplot library for Python (see full error below) in a Jupyter Notebook, running Python 3.5.2. with the following import statements:
%matplotlib inline
from ggplot import *
The graph still renders, but I would like to eliminate the error, or hide it if its not causing a major conflict.
The full error is below. Many thanks in advance :)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
//anaconda/lib/python3.5/site-packages/IPython/core/formatters.py in __call__(self, obj)
697 type_pprinters=self.type_printers,
698 deferred_pprinters=self.deferred_printers)
--> 699 printer.pretty(obj)
700 printer.flush()
701 return stream.getvalue()
//anaconda/lib/python3.5/site-packages/IPython/lib/pretty.py in pretty(self, obj)
381 if callable(meth):
382 return meth(obj, self, cycle)
--> 383 return _default_pprint(obj, self, cycle)
384 finally:
385 self.end_group()
//anaconda/lib/python3.5/site-packages/IPython/lib/pretty.py in _default_pprint(obj, p, cycle)
501 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
502 # A user-provided repr. Find newlines and replace them with p.break_()
--> 503 _repr_pprint(obj, p, cycle)
504 return
505 p.begin_group(1, '<')
//anaconda/lib/python3.5/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle)
692 """A pprint that just redirects to the normal repr function."""
693 # Find newlines and replace them with p.break_()
--> 694 output = repr(obj)
695 for idx,output_line in enumerate(output.splitlines()):
696 if idx:
//anaconda/lib/python3.5/site-packages/ggplot/ggplot.py in __repr__(self)
113 Evaluates patsy expressions within the aesthetics. For example, 'x + 1'
114 , 'factor(x)', or 'pd.cut(price, bins=10)')
--> 115 """
116 for key, item in self._aes.items():
117 if item not in self.data:
//anaconda/lib/python3.5/site-packages/ggplot/ggplot.py in make(self)
//anaconda/lib/python3.5/site-packages/ggplot/ggplot.py in apply_axis_labels(self)
269 i, j = self.subplots.shape
270 i, j = int((i - 1) / 2), int(j - 1)
--> 271 ax = self.subplots[i][j]
272 make_legend(ax, legend)
273 elif self.facets.rowvar:
NameError: name 'unicode' is not defined
If you have anaconda installed try installing the code-forge version. I was able to fix this same problem by switching to that version for python 3.5
conda install -c conda-forge ggplot
Hope that helps
After a long period where things went OK (I mean here I could pip install packages and then use them in a jupyter notebook with the import statement), I ran into multiple problems recently.
I think this happened when I upgraded my anaconda install from Continuum Analytics (though not sure)
I get error reports for basic imports like pandas or matplotlib like
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-adcb0ce40833> in <module>()
1 # Plot softmax curves
----> 2 import matplotlib.pyplot as plt
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/site- packages/matplotlib/__init__.py in <module>()
1129
1130 # this is the instance used by the matplotlib classes
-> 1131 rcParams = rc_params()
1132
1133 if rcParams['examples.directory']:
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/site-packages/matplotlib/__init__.py in rc_params(fail_on_error)
973 return ret
974
--> 975 return rc_params_from_file(fname, fail_on_error)
976
977
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/site- packages/matplotlib/__init__.py in rc_params_from_file(fname, fail_on_error, use_default_template)
1098 parameters specified in the file. (Useful for updating dicts.)
1099 """
-> 1100 config_from_file = _rc_params_in_file(fname, fail_on_error)
1101
1102 if not use_default_template:
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/site-packages/matplotlib/__init__.py in _rc_params_in_file(fname, fail_on_error)
1016 cnt = 0
1017 rc_temp = {}
-> 1018 with _open_file_or_url(fname) as fd:
1019 try:
1020 for line in fd:
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/contextlib.pyc in __enter__(self)
15 def __enter__(self):
16 try:
---> 17 return self.gen.next()
18 except StopIteration:
19 raise RuntimeError("generator didn't yield")
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/site- packages/matplotlib/__init__.py in _open_file_or_url(fname)
998 else:
999 fname = os.path.expanduser(fname)
-> 1000 encoding = locale.getdefaultlocale()[1]
1001 if encoding is None:
1002 encoding = "utf-8"
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/locale.pyc in getdefaultlocale(envvars)
541 else:
542 localename = 'C'
--> 543 return _parse_localename(localename)
544
545
/Users/peterhirt/anaconda/envs/tensorflow/lib/python2.7/locale.pyc in _parse_localename(localename)
473 elif code == 'C':
474 return None, None
--> 475 raise ValueError, 'unknown locale: %s' % localename
476
477 def _build_localename(localetuple):
ValueError: unknown locale: UTF-8
So, I tried to use a specific environment where I installed first the python version I wanted to use and then added things like tensorflow (which went very well)
I do this by
conda create tensorflow python=2.7
this creates me a environment called tensorflow and install python version 2.7
then I activate the envrionment by
source activate tensorflow
Then, I added matplotlib with
pip install matplotlib
and i get again this error
I am lost. I think it has to do with incompatible packages but I cannot go around this and solve it.
Can someone give me a helping hand please
Thanks in advance
Peter
I recently installed Sage 6.3 on my Fedora 21 machine. I'm using version 6.3, which is slightly outdated, because it is the most recent thing available in yum's repositories. I also installed Mathematica on the same computer in the hope of being able to call it from within Sage.
Mathematica's terminal interface using the math command works, which according to this reference page should be all that I need. However, when I tell Sage to use mathematica either from the Sage command line or the notebook, Sage hangs. Here's a sample of my interaction with the terminal (the traceback is horrible, as is frequently the case in Sage):
sage: mathematica('hello world')
^CInterrupting Mathematica...
^C---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-1-9208bb19d841> in <module>()
----> 1 mathematica('hello world')
/usr/lib64/python2.7/site-packages/sage/interfaces/interface.pyc in __call__(self, x, name)
197
198 if isinstance(x, basestring):
--> 199 return cls(self, x, name=name)
200 try:
201 return self._coerce_from_special_method(x)
/usr/lib64/python2.7/site-packages/sage/interfaces/expect.pyc in __init__(self, parent, value, is_name, name)
1310 else:
1311 try:
-> 1312 self._name = parent._create(value, name=name)
1313 # Convert ValueError and RuntimeError to TypeError for
1314 # coercion to work properly.
/usr/lib64/python2.7/site-packages/sage/interfaces/interface.pyc in _create(self, value, name)
387 def _create(self, value, name=None):
388 name = self._next_var_name() if name is None else name
--> 389 self.set(name, value)
390 return name
391
/usr/lib64/python2.7/site-packages/sage/interfaces/mathematica.pyc in set(self, var, value)
508 cmd = '%s=%s;'%(var,value)
509 #out = self.eval(cmd)
--> 510 out = self._eval_line(cmd, allow_use_file=True)
511 if len(out) > 8:
512 raise TypeError("Error executing code in Mathematica\nCODE:\n\t%s\nMathematica ERROR:\n\t%s"%(cmd, out))
/usr/lib64/python2.7/site-packages/sage/interfaces/mathematica.pyc in _eval_line(self, line, allow_use_file, wait_for_prompt, restart_if_needed)
535 def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=False):
536 s = Expect._eval_line(self, line,
--> 537 allow_use_file=allow_use_file, wait_for_prompt=wait_for_prompt)
538 return str(s).strip('\n')
539
/usr/lib64/python2.7/site-packages/sage/interfaces/expect.pyc in _eval_line(self, line, allow_use_file, wait_for_prompt, restart_if_needed)
890 out = ''
891 except KeyboardInterrupt:
--> 892 self._keyboard_interrupt()
893 raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self)
894 if self._terminal_echo:
/usr/lib64/python2.7/site-packages/sage/interfaces/mathematica.pyc in _keyboard_interrupt(self)
420 e = self._expect
421 e.sendline(chr(3)) # send ctrl-c
--> 422 e.expect('Interrupt> ')
423 e.sendline("a") # a -- abort
424 e.expect(self._prompt)
/usr/lib64/sagemath/site-packages/pexpect.pyc in expect(self, pattern, timeout, searchwindowsize)
914 """
915 compiled_pattern_list = self.compile_pattern_list(pattern)
--> 916 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
917
918 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
/usr/lib64/sagemath/site-packages/pexpect.pyc in expect_list(self, pattern_list, timeout, searchwindowsize)
965 raise TIMEOUT ('Timeout exceeded in expect_list().')
966 # Still have time left, so read more data
--> 967 c = self.read_nonblocking (self.maxread, timeout)
968 incoming = incoming + c
969 if timeout is not None:
/usr/lib64/sagemath/site-packages/pexpect.pyc in read_nonblocking(self, size, timeout)
546 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
547
--> 548 r, w, e = select.select([self.child_fd], [], [], timeout)
549 if not r:
550 if not self.isalive():
/usr/lib64/python2.7/site-packages/sage/ext/c_lib.so in sage.ext.c_lib.sage_python_check_interrupt (build/cythonized/sage/ext/c_lib.c:1683)()
/usr/lib64/python2.7/site-packages/sage/ext/c_lib.so in sage.ext.c_lib.sig_raise_exception (build/cythonized/sage/ext/c_lib.c:769)()
KeyboardInterrupt:
sage:
The equivalent in Mathematica's own interface works just fine:
Mathematica 10.1.0 for Linux x86 (64-bit)
Copyright 1988-2015 Wolfram Research, Inc.
In[1]:= hello world
Out[1]= hello world
In[2]:=
Am I doing something wrong, or is this a bug in Sage? Would downloading and building the latest version (6.7) manually fix the problem?
EDIT:
I am using Mathematica 10.1.0. Could it be that be my problem, i.e. the older version of Sage doesn't know how to handle the newer version of Mathematica?
According to Trac 16703, this problem should be fixed in the latest Sage. I don't personally have a copy of Mathematica to test this on.