Skip to content

Commit

Permalink
Merge pull request #44 from minrk/warn-on-none
Browse files Browse the repository at this point in the history
Don't enable extension if sys.__stdout|err__ is None
  • Loading branch information
minrk authored Mar 30, 2021
2 parents 33f31f5 + c2f7b74 commit e583419
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion wurlitzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,9 @@ def stop_sys_pipes():
_mighty_wurlitzer = None


_extension_enabled = False


def load_ipython_extension(ip):
"""Register me as an IPython extension
Expand All @@ -366,22 +369,33 @@ def load_ipython_extension(ip):
Use: %load_ext wurlitzer
"""
global _extension_enabled

if not getattr(ip, 'kernel', None):
warnings.warn("wurlitzer extension doesn't do anything in terminal IPython")
return
for name in ("__stdout__", "__stderr__"):
if getattr(sys, name) is None:
warnings.warn("sys.{} is None. Wurlitzer can't capture output without it.")
return

ip.events.register('pre_execute', sys_pipes_forever)
ip.events.register('post_execute', stop_sys_pipes)
_extension_enabled = True


def unload_ipython_extension(ip):
"""Unload me as an IPython extension
Use: %unload_ext wurlitzer
"""
if not getattr(ip, 'kernel', None):
global _extension_enabled
if not _extension_enabled:
return

ip.events.unregister('pre_execute', sys_pipes_forever)
ip.events.unregister('post_execute', stop_sys_pipes)
# sys_pipes_forever was called in pre_execute
# after unregister we need to call it explicitly:
stop_sys_pipes()
_extension_enabled = False

0 comments on commit e583419

Please sign in to comment.