def interface_shell_embed(interface): """ Returns an IPython shell which uses a Sage interface on the backend to perform the evaluations. It uses :class:`InterfaceShellTransformer` to transform the input into the appropriate ``interface.eval(...)`` input. EXAMPLES:: sage: from sage.misc.interpreter import interface_shell_embed sage: shell = interface_shell_embed(gap) sage: shell.run_cell('List( [1..10], IsPrime )') [ false, true, true, false, true, false, true, false, false, false ] """ try: cfg = Config(get_ipython().config) except NameError: cfg = Config(DEFAULT_SAGE_CONFIG) cfg.PromptManager['in_template'] = interface.name() + ': ' ipshell = InteractiveShellEmbed(config=cfg, banner1='\n --> Switching to %s <--\n\n'%interface, exit_msg = '\n --> Exiting back to Sage <--\n') ipshell.interface = interface while ipshell.prefilter_manager.transformers: ipshell.prefilter_manager.transformers.pop() while ipshell.prefilter_manager.checkers: ipshell.prefilter_manager.checkers.pop() ipshell.ex('from sage.all import *') InterfaceShellTransformer(shell=ipshell, prefilter_manager=ipshell.prefilter_manager, config=cfg) return ipshell
def __init__(self, exec_lines=None): self.cout = StringIO() if exec_lines is None: exec_lines = [] # Create config object for IPython config = Config() config.InteractiveShell.autocall = False config.InteractiveShell.autoindent = False config.InteractiveShell.colors = 'NoColor' # create a profile so instance history isn't saved tmp_profile_dir = tempfile.mkdtemp(prefix='profile_') profname = 'auto_profile_sphinx_build' pdir = os.path.join(tmp_profile_dir, profname) profile = ProfileDir.create_profile_dir(pdir) # Create and initialize global ipython, but don't start its mainloop. # This will persist across different EmbededSphinxShell instances. IP = InteractiveShell.instance(config=config, profile_dir=profile) atexit.register(self.cleanup) # io.stdout redirect must be done after instantiating InteractiveShell io.stdout = self.cout io.stderr = self.cout # For debugging, so we can see normal output, use this: #from IPython.utils.io import Tee #io.stdout = Tee(self.cout, channel='stdout') # dbg #io.stderr = Tee(self.cout, channel='stderr') # dbg # Store a few parts of IPython we'll need. self.IP = IP self.user_ns = self.IP.user_ns self.user_global_ns = self.IP.user_global_ns self.input = '' self.output = '' self.tmp_profile_dir = tmp_profile_dir self.is_verbatim = False self.is_doctest = False self.is_suppress = False # Optionally, provide more detailed information to shell. # this is assigned by the SetUp method of IPythonDirective # to point at itself. # # So, you can access handy things at self.directive.state self.directive = None # on the first call to the savefig decorator, we'll import # pyplot as plt so we can make a call to the plt.gcf().savefig self._pyplot_imported = False # Prepopulate the namespace. for line in exec_lines: self.process_input_line(line, store_history=False)
def interface_shell_embed(interface): """ Returns an IPython shell which uses a Sage interface on the backend to perform the evaluations. It uses :class:`InterfaceShellTransformer` to transform the input into the appropriate ``interface.eval(...)`` input. INPUT: - ``interface`` -- A Sage ``PExpect`` interface instance. EXAMPLES:: sage: from sage.misc.interpreter import interface_shell_embed sage: shell = interface_shell_embed(gap) sage: shell.run_cell('List( [1..10], IsPrime )') [ false, true, true, false, true, false, true, false, false, false ] """ try: cfg = Config(get_ipython().config) except NameError: cfg = Config(DEFAULT_SAGE_CONFIG) cfg.PromptManager['in_template'] = interface.name() + ': ' ipshell = InteractiveShellEmbed( config=cfg, banner1='\n --> Switching to %s <--\n\n' % interface, exit_msg='\n --> Exiting back to Sage <--\n') ipshell.interface = interface while ipshell.prefilter_manager.transformers: ipshell.prefilter_manager.transformers.pop() while ipshell.prefilter_manager.checkers: ipshell.prefilter_manager.checkers.pop() ipshell.ex('from sage.all import *') InterfaceShellTransformer(shell=ipshell, prefilter_manager=ipshell.prefilter_manager, config=cfg) return ipshell
def __init__(self): self.cout = cStringIO.StringIO() # Create config object for IPython config = Config() config.Global.display_banner = False config.Global.exec_lines = [ 'import numpy as np', 'from pylab import *' ] config.InteractiveShell.autocall = False config.InteractiveShell.autoindent = False config.InteractiveShell.colors = 'NoColor' config.InteractiveShell.cache_size = 0 # create a profile so instance history isn't saved tmp_profile_dir = tempfile.mkdtemp(prefix='profile_') profname = 'auto_profile_sphinx_build' pdir = os.path.join(tmp_profile_dir, profname) profile = ProfileDir.create_profile_dir(pdir) # Create and initialize ipython, but don't start its mainloop IP = InteractiveShell.instance(config=config, profile_dir=profile) # io.stdout redirect must be done *after* instantiating # InteractiveShell io.stdout = self.cout io.stderr = self.cout # For debugging, so we can see normal output, use this: # from IPython.utils.io import Tee # io.stdout = Tee(self.cout, channel='stdout') # dbg # io.stderr = Tee(self.cout, channel='stderr') # dbg # Store a few parts of IPython we'll need. self.IP = IP self.user_ns = self.IP.user_ns self.user_global_ns = self.IP.user_global_ns self.input = '' self.output = '' self.is_verbatim = False self.is_doctest = False self.is_suppress = False # on the first call to the savefig decorator, we'll import # pyplot as plt so we can make a call to the plt.gcf().savefig self._pyplot_imported = False
def load_config_file(self, *args, **kwds): from IPython.config.loader import PyFileConfigLoader, ConfigFileNotFound from IPython.core.profiledir import ProfileDir from IPython.utils.path import get_ipython_dir conf = Config() conf._merge(DEFAULT_SAGE_CONFIG) conf._merge(self.command_line_config) # Get user config. sage_profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), 'sage').location try: cl = PyFileConfigLoader('ipython_config.py', sage_profile_dir) conf._merge(cl.load_config()) except ConfigFileNotFound: pass self.update_config(conf)
def __init__(self): self.cout = cStringIO.StringIO() Term.cout = self.cout Term.cerr = self.cout # For debugging, so we can see normal output, use this: # from IPython.utils.io import Tee # Term.cout = Tee(self.cout, channel='stdout') # dbg # Term.cerr = Tee(self.cout, channel='stderr') # dbg # Create config object for IPython config = Config() config.Global.display_banner = False config.Global.exec_lines = [ "import numpy as np", "from pylab import *" ] config.InteractiveShell.autocall = False config.InteractiveShell.autoindent = False config.InteractiveShell.colors = "NoColor" # Create and initialize ipython, but don't start its mainloop IP = InteractiveShell.instance(config=config) # Store a few parts of IPython we'll need. self.IP = IP self.user_ns = self.IP.user_ns self.user_global_ns = self.IP.user_global_ns self.input = "" self.output = "" self.is_verbatim = False self.is_doctest = False self.is_suppress = False # on the first call to the savefig decorator, we'll import # pyplot as plt so we can make a call to the plt.gcf().savefig self._pyplot_imported = False # we need bookmark the current dir first so we can save # relative to it self.process_input_line("bookmark ipy_basedir") self.cout.seek(0) self.cout.truncate(0)
################################################################### # Default configuration ################################################################### DEFAULT_SAGE_CONFIG = Config( PromptManager = Config( in_template = 'sage: ', in2_template = '....: ', justify = False, out_template = ''), TerminalIPythonApp = Config( display_banner = False, verbose_crash = True, test_shell = False, shell_class = SageTerminalInteractiveShell, ), InteractiveShell = Config( ast_node_interactivity = 'all', colors = 'LightBG' if sys.stdout.isatty() else 'NoColor', confirm_exit = False, separate_in = ''), InteractiveShellApp = Config(extensions=[SAGE_EXTENSION]), ) ################################################################### # Transformers used in the SageInputSplitter ################################################################### from IPython.core.inputtransformer import (CoroutineInputTransformer,
def __init__(self, **kwargs): self.command_line_config = kwargs.get('config', Config()) super(SageTerminalApp, self).__init__(**kwargs)
app, contact_name, contact_email, bug_tracker, show_crash_traceback=False) self.crash_report_fname = 'Sage_crash_report.txt' DEFAULT_SAGE_CONFIG = Config( PromptManager=Config(in_template='sage: ', in2_template='....: ', justify=False, out_template=''), TerminalIPythonApp=Config(display_banner=False, verbose_crash=True), TerminalInteractiveShell=Config( ast_node_interactivity='all', colors='LightBG' if sys.stdout.isatty() else 'NoColor', confirm_exit=False, separate_in=''), # The extension is *always* loaded for SageTerminalApp # See the code for SageTerminalApp.init_shell #InteractiveShellApp = Config(extensions=['sage.misc.sage_extension']), ) class SageTerminalApp(TerminalIPythonApp): name = u'Sage' crash_handler_class = SageCrashHandler test_shell = False def __init__(self, **kwargs):
# Our own from IPython import Config, InteractiveShell from IPython.utils.io import Term # ----------------------------------------------------------------------------- # Globals # ----------------------------------------------------------------------------- sphinx_version = sphinx.__version__.split(".") # The split is necessary for sphinx beta versions where the string is # '6b1' sphinx_version = tuple( [int(re.split("[a-z]", x)[0]) for x in sphinx_version[:2]]) COMMENT, INPUT, OUTPUT = range(3) CONFIG = Config() rgxin = re.compile("In \[(\d+)\]:\s?(.*)\s*") rgxout = re.compile("Out\[(\d+)\]:\s?(.*)\s*") fmtin = "In [%d]:" fmtout = "Out[%d]:" # ----------------------------------------------------------------------------- # Functions and class declarations # ----------------------------------------------------------------------------- def block_parser(part): """ part is a string of ipython text, comprised of at most one input, one ouput, comments, and blank lines. The block parser parses the text into a list of::
from config import settings, dbconf, bsconf from models import * import models database = Database(**dbconf) blobstore = None # Blobstore(bsconf.nodes, **bsconf.opts) models.initialize(database, blobstore) # Drop into IPython from IPython import embed from IPython import Config config = Config() prompt = config.PromptManager prompt.in_template = ">>> " prompt.in2_template = "... " prompt.out_template = "" prompt.justify = False ishell = config.InteractiveShell ishell.confirm_exit = False mode = ("debug" if settings["debug"] else "default") banner = "Loaded %s environment\nType %%quickref for help" % mode del prompt, ishell # clean up namespace
SageCrashHandler, DEFAULT_SAGE_CONFIG, SageInteractiveShell, ) # The notebook Jinja2 templates and static files TEMPLATE_PATH = os.path.join(SAGE_EXTCODE, 'notebook-ipython', 'templates') STATIC_PATH = os.path.join(SAGE_EXTCODE, 'notebook-ipython', 'static') DOCS_PATH = os.path.join(SAGE_DOC, 'output', 'html', 'en') # Note: sage.repl.interpreter.DEFAULT_SAGE_CONFIG will be applied, too DEFAULT_SAGE_NOTEBOOK_CONFIG = Config( SageNotebookApp = Config( # log_level = 'DEBUG', # if you want more logs # open_browser = False, # if you want to avoid browser restart webapp_settings = Config( template_path = TEMPLATE_PATH, ), extra_static_paths = [STATIC_PATH, DOCS_PATH], ), ) class SageNotebookApp(NotebookApp): name = u'sage-notebook-ipython' crash_handler_class = SageCrashHandler def load_config_file(self, *args, **kwds): r""" Merges a config file with the default sage notebook config. EXAMPLES::