Skip to content

Instantly share code, notes, and snippets.

@MSeifert04
Last active February 8, 2017 06:54
Show Gist options
  • Save MSeifert04/38829e9d9ad97e5337cb3df0208873ba to your computer and use it in GitHub Desktop.
Save MSeifert04/38829e9d9ad97e5337cb3df0208873ba to your computer and use it in GitHub Desktop.
class Streams(object):
def _initialize_attributes(self):
try:
from IPython import get_ipython
except ImportError:
pass
try:
get_ipython()
except NameError:
self._OutStream = None
self._IPythonIOStream = None
else:
from IPython import version_info
ipython_major_version = version_info[0]
try:
from ipykernel.iostream import OutStream
self._OutStream = OutStream
except ImportError:
try:
from IPython.zmq.iostream import OutStream
self._OutStream = OutStream
except ImportError:
if ipython_major_version < 4:
try:
from IPython.kernel.zmq.iostream import OutStream
self._OutStream = OutStream
except ImportError:
self._OutStream = None
else:
self._OutStream = None
if self.OutStream is not None:
from IPython.utils import io as ipyio
# On Windows in particular this is necessary, as the io.stdout stream
# in IPython gets hooked up to some pyreadline magic to handle colors
self._IPythonIOStream = ipyio.IOStream
else:
self._OutStream = None
self._IPythonIOStream = None
# On Windows, in IPython 2 the standard I/O streams will wrap
# pyreadline.Console objects if pyreadline is available; this should
# be considered a TTY
try:
from pyreadyline.console import Console as PyreadlineConsole
self._PyreadlineConsole = PyreadlineConsole
except ImportError:
# Just define a dummy class
class PyreadlineConsole(object): pass
self._PyreadlineConsole = PyreadlineConsole
@property
def OutStream(self):
try:
return self._OutStream
except AttributeError:
self._initialize_attributes()
return self._OutStream
@property
def IPythonIOStream(self):
try:
return self._IPythonIOStream
except AttributeError:
self._initialize_attributes()
return self._IPythonIOStream
@property
def PyreadlineConsole(self):
try:
return self._PyreadlineConsole
except AttributeError:
self._initialize_attributes()
return self._PyreadlineConsole
streams = Streams() # global variable (Singleton)
# in the other functions just use:
streams.PyreadlineConsole
streams.OutStream
streams.IPythonIOStream
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment