Jupyter notebook `pylab inline` gives `matplotlib` error - python

Previously, I was working on a Jupyter notebook project on a mac running Python 3.7.
Today, when I wanted to load the notebook's %pylab inline machinery, I received the error:
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-a6e0d37a4680> in <module>
----> 1 get_ipython().run_line_magic('pylab', 'inline')
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2283 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2284 with self.builtin_trap:
-> 2285 result = fn(*args,**kwargs)
2286 return result
2287
<decorator-gen-108> in pylab(self, line)
/Library/Frameworks/Python.framework/Versions/3.7/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):
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- packages/IPython/core/magics/pylab.py in pylab(self, line)
153 import_all = not args.no_import_all
154
--> 155 gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
156 self._show_matplotlib_backend(args.gui, backend)
157 print ("Populating the interactive namespace from numpy and matplotlib")
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/IPython/core/interactiveshell.py in enable_pylab(self, gui, import_all, welcome_message)
3390 from IPython.core.pylabtools import import_pylab
3391
-> 3392 gui, backend = self.enable_matplotlib(gui)
3393
3394 # We want to prevent the loading of pylab to pollute the user's
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui)
3339 """
3340 from IPython.core import pylabtools as pt
-> 3341 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3342
3343 if gui != 'inline':
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/IPython/core/pylabtools.py in find_gui_and_backend(gui, gui_select)
274 """
275
--> 276 import matplotlib
277
278 if gui and gui != 'auto':
ModuleNotFoundError: No module named 'matplotlib'
I've tried looking for solutions online.
I have removed Python 3.6, reinstalled brew from scratch, reinstalled jupyter from scratch using the terminal but to no solution.
Is there a solution?

Don't use %pylab, it is deprecated. Use either:
%matplotlib inline
or %matplotlib notebook

Related

ipynb `%load_ext rpy2.ipython` errors "... 3 arguments passed to .Internal(gettext) which requires 2"

I use Anaconda Jupyter notebook via VSCode or directly via browser.
I installed rpy2 via conda as:
conda install -c r r-essentials rpy2 --yes
Then in a Python cell of Jupyter Notebook, I ran:
%load_ext rpy2.ipython
And got
R[write to console]: Error in gettext(fmt, domain = domain, trim = trim) :
3 arguments passed to .Internal(gettext) which requires 2
Details
I use Windows 10. I have a separate R installation on my computer too.
In ipynb, the same error appears if I run:
import rpy2.robjects as robjects
More details on the error:
%load_ext rpy2.ipython
R[write to console]: Error in gettext(fmt, domain = domain, trim = trim) :
3 arguments passed to .Internal(gettext) which requires 2
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
RRuntimeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_18052\1837600852.py in <cell line: 1>()
----> 1 get_ipython().run_line_magic('load_ext', 'rpy2.ipython')
c:\Users\user\anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2415 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2416 with self.builtin_trap:
-> 2417 result = fn(*args, **kwargs)
2418 return result
2419
c:\Users\user\anaconda3\lib\site-packages\decorator.py in fun(*args, **kw)
230 if not kwsyntax:
231 args, kw = fix(args, kw, sig)
--> 232 return caller(func, *(extras + args), **kw)
233 fun.__name__ = func.__name__
234 fun.__doc__ = func.__doc__
c:\Users\user\anaconda3\lib\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):
...
812
RRuntimeError: Error in gettext(fmt, domain = domain, trim = trim) :
3 arguments passed to .Internal(gettext) which requires 2
Other things I tried:
# Works:
import rpy2
print(rpy2.__version__)
# Returns:
3.5.1
import rpy2.situation
for row in rpy2.situation.iter_info():
print(row)
# Returns:
rpy2 version:
3.5.1
Python version:
3.9.13 | packaged by conda-forge | (main, May 27 2022, 16:50:36) [MSC v.1929 64 bit (AMD64)]
Looking for R's HOME:
Environment variable R_HOME: None
InstallPath in the registry: C:\Program Files\R\R-4.2.2
Environment variable R_USER: None
Environment variable R_LIBS_USER: None
Unable to determine R library path: Command '('C:\\Users\\user\\anaconda3\\lib\\R\\bin\\Rscript', '-e', 'cat(Sys.getenv("LD_LIBRARY_PATH"))')' returned non-zero exit status 1.
R version:
In the PATH: R version 4.1.3 (2022-03-10) -- "One Push-Up"
Loading R library from rpy2: OK
Additional directories to load R packages from:
None
C extension compilation:
include:
['C:/PROGRA~1/R/R-4.2.2/include', 'C:/PROGRA~1/R/R-4.2.2/include/x64']
libraries:
['R', 'm']
library_dirs:
['C:/PROGRA~1/R/R-4.2.2/bin/x64']
extra_compile_args:
[]
extra_link_args:
[]
A similar issue with no answer is here.
Might be related but is related to continuous integration: https://github.com/rpy2/rpy2/issues/874

matplotlib.pyplot import failed in ipython but works in jupyter

I get this long error when i try importing pyplot in ipython. Everything works fine when i try the same in jupyter notebook.
I think I've tried all the suggestions I found about pyplot import errors. I tried reinstalling matplotlib, ipykernel, zmq etc etc., I tried rolling back to old versions. I've tried matching sys.path from notebook and my ipython kernel, but no success.
I'm using python 3.7, windows 10, ConEmu for ipython kernel.
from matplotlib import pyplot
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-02aaac1810fb> in <module>
----> 1 from matplotlib import pyplot
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in <module>
2347 dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
2348 # Set up the backend.
-> 2349 switch_backend(rcParams["backend"])
2350
2351 # Just to be safe. Interactive mode can be turned on without
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in switch_backend(newbackend)
219 else "matplotlib.backends.backend_{}".format(newbackend.lower()))
220
--> 221 backend_mod = importlib.import_module(backend_name)
222 Backend = type(
223 "Backend", (matplotlib.backends._Backend,), vars(backend_mod))
C:\ProgramData\Python3\Continuum\anaconda3\lib\importlib\__init__.py in import_module(name, package)
125 break
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
128
129
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\backends\backend_tkagg.py in <module>
1 from . import _backend_tk
----> 2 from .backend_agg import FigureCanvasAgg
3 from ._backend_tk import (
4 _BackendTk, FigureCanvasTk, FigureManagerTk, NavigationToolbar2Tk)
5
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in <module>
43
44 if _has_pil:
---> 45 from PIL import Image
46
47 backend_version = 'v2.2'
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\PIL\Image.py in <module>
93 # Also note that Image.core is not a publicly documented interface,
94 # and should be considered private and subject to change.
---> 95 from . import _imaging as core
96
97 if __version__ != getattr(core, "PILLOW_VERSION", None):
ImportError: DLL load failed: The specified module could not be found.

Unable to import matplotlib.animation

I'm new to both python and OSX, so if i'm not understanding super basic stuff please forgive me.
I'm using python 2.7.12 on a fresh install from Homebrew. I also used Homebrew to install ipython, ffmpeg and libav (installs avconv, which I believe is required for what i'm trying to do).
I've used pip to install Scipy, numpy (which I think comes with scipy anyway?) and matplotlib
I'm running El Capitan v10.11.6
Background (for some context):
I'm running some hydrodynamic simulations that output a bunch of binary files. I wan't to stitch them together to create a movie. Lucky for me, one of my colleagues has already written a tidy little python script to do so (which he wrote in ipython).
Problem:
When trying to run
import matplotlib.animation
The script just hangs, and matplotlib animation never gets imported. I've tried changing the backend via
import matplotlib
matplotlib.use('tkagg')
import matplotlib.animaton
I've tried various backends that I got by running code from List of all available matplotlib backends
I have also tried import matplotlib.pyplot hangs (updating fc-lists)
Lastly, and i'm not sure if this is helpful, but leaving ipython trying to import matplot.animation for about 10 minutes, and then terminating it outputs the following
In [3]: import matplotlib.animation
^C---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-3-64e90e455a86> in <module>()
----> 1 import matplotlib.animation
/usr/local/lib/python2.7/site-packages/matplotlib/animation.py in <module>()
589
590 #writers.register('imagemagick')
--> 591 class ImageMagickWriter(MovieWriter, ImageMagickBase):
592 def _args(self):
593 return ([self.bin_path(),
/usr/local/lib/python2.7/site-packages/matplotlib/animation.py in wrapper(writerClass)
73 def register(self, name):
74 def wrapper(writerClass):
---> 75 if writerClass.isAvailable():
76 self.avail[name] = writerClass
77 return writerClass
/usr/local/lib/python2.7/site-packages/matplotlib/animation.py in isAvailable(cls)
284 stderr=subprocess.PIPE,
285 creationflags=subprocess_creation_flags)
--> 286 p.communicate()
287 return True
288 except OSError:
/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/ lib/python2.7/subprocess.pyc in communicate(self, input)
798 return (stdout, stderr)
799
--> 800 return self._communicate(input)
801
802
/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.pyc in _communicate(self, input)
1417 stdout, stderr = self._communicate_with_poll(input)
1418 else:
-> 1419 stdout, stderr = self._communicate_with_select(input)
1420
1421 # All data exchanged. Translate lists into strings.
/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.pyc in _communicate_with_select(self, input)
1518 while read_set or write_set:
1519 try:
-> 1520 rlist, wlist, xlist = select.select(read_set, write_set, [])
1521 except select.error, e:
1522 if e.args[0] == errno.EINTR:
KeyboardInterrupt:
If you give any of this a second thought, even if you aren't able to help, thank you very much!
Do you have more than one version of Python installed? I would check your python path. Make sure matplotlib is in 2.7 in this case.
This might be relevant too -- import matplotlib.pyplot hangs

Error while importing matplotlib in Canopy - rc_params_from_file()

I have the Enthought Canopy installed on my Ubuntu 14.04. I'm trying to run sample matplotlib programs (from the library's website). Every attempt of running the program makes the Canopy's command prompt display following message:
TypeError Traceback (most recent call last)
/home/guras/Canopy/appdata/canopy-1.4.1.1975.rh5-x86_64/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
202 else:
203 filename = fname
--> 204 __builtin__.execfile(filename, *where)
/home/guras/Python programy/pierwszy.py in <module>()
4 This example uses the Fahrenheit and Celsius scales.
5 """
----> 6 import matplotlib.pyplot as plt
7 import numpy as np
8
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/pyplot.py in <module>()
26 import matplotlib
27 import matplotlib.colorbar
---> 28 from matplotlib import style
29 from matplotlib import _pylab_helpers, interactive
30 from matplotlib.cbook import dedent, silent_list, is_string_like, is_numlike
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/__init__.py in <module>()
1 from __future__ import absolute_import
2
----> 3 from .core import use, context, available, library, reload_library
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/core.py in <module>()
147 # Load style library
148 # ==================
--> 149 _base_library = load_base_library()
150
151 library = None
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/core.py in load_base_library()
92 """Load style library defined in this package."""
93 library = dict()
---> 94 library.update(read_style_directory(BASE_LIBRARY_PATH))
95 return library
96
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/core.py in read_style_directory(style_dir)
125 styles = dict()
126 for path, name in iter_style_files(style_dir):
--> 127 styles[name] = rc_params_from_file(path, use_default_template=False)
128 return styles
129
TypeError: **rc_params_from_file() got an unexpected keyword argument 'use_default_template'**
Any ideas how to fix it?
The use_default_template keyword parameter was added to the rc_params_from_file function in matplotlib version 1.4.0rc1.
Most likely, your version of matplotlib is older than 1.4.0rc1 and needs to be upgraded.
If you have more than one installation of matplotlib installed, you'll need to make sure the directory containing the newer version is listed earlier than the older version in sys.path, or perhaps, simply delete the older version of matplotlib.
Use the Canopy Package Manager to update matplotlib to the latest version.

AttributeError when running unittest sample in iPy Notebook

I am new to iPython and trying to help another developer get started and we are both hitting same issues.
We are attempting to run a python unittest sample in iPython from https://docs.python.org/2/library/unittest.html#basic-example
The code runs just fine from command line on windows and ubuntu without ANY modifications
Exact same code from iPy notebook generates following exception:
AttributeError: 'module' object has no attribute '/home/myuser/'
The filename is: /home/myuser/example_unittest.ipynb
I have noodled the iPython docs and google with no luck as of the moment. Any debugging tips, or clues to solving this issue are appreciated.
(full stack):
AttributeError Traceback (most recent call last)
<ipython-input-2-39bc0ec16f11> in <module>()
28
29 if __name__ == '__main__':
---> 30 unittest.main()
31
/usr/lib/python2.7/unittest/main.pyc in __init__(self, module, defaultTest, argv, testRunner, testLoader, exit, verbosity, failfast, catchbreak, buffer)
92 self.testLoader = testLoader
93 self.progName = os.path.basename(argv[0])
---> 94 self.parseArgs(argv)
95 self.runTests()
96
/usr/lib/python2.7/unittest/main.pyc in parseArgs(self, argv)
147 else:
148 self.testNames = (self.defaultTest,)
--> 149 self.createTests()
150 except getopt.error, msg:
151 self.usageExit(msg)
/usr/lib/python2.7/unittest/main.pyc in createTests(self)
156 else:
157 self.test = self.testLoader.loadTestsFromNames(self.testNames,
--> 158 self.module)
159
160 def _do_discovery(self, argv, Loader=loader.TestLoader):
/usr/lib/python2.7/unittest/loader.pyc in loadTestsFromNames(self, names, module)
126 of string specifiers. See 'loadTestsFromName()'.
127 """
--> 128 suites = [self.loadTestsFromName(name, module) for name in names]
129 return self.suiteClass(suites)
130
/usr/lib/python2.7/unittest/loader.pyc in loadTestsFromName(self, name, module)
98 obj = module
99 for part in parts:
--> 100 parent, obj = obj, getattr(obj, part)
101
102 if isinstance(obj, types.ModuleType):
AttributeError: 'module' object has no attribute '/home/myuser/'
unittest.main() is primarily for command line execution.
In order to run a unittest in the ipython notebook, remove the if __name__ == '__main__' part of the code and, in a new cell, create a test suite and then run it using TextTestRunner,
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner().run(suite)
The reason you are getting that error because of unittest.main checks for arguments (sys.argv). It's what starts iPython or Jupyter.
Change your code to:
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
In the notebook, you will also want to include exit=False to prevent unittest.main from trying to shutdown the kernel process:

Categories