Пример #1
0
    def __init__(self,
                 name,
                 usage=None,
                 rc=Struct(opts=None, args=None),
                 user_ns=None,
                 user_global_ns=None,
                 banner2='',
                 **kw):
        """Similar to the normal InteractiveShell, but with threading control"""

        InteractiveShell.__init__(self, name, usage, rc, user_ns,
                                  user_global_ns, banner2)

        # A queue to hold the code to be executed.
        self.code_queue = Queue.Queue()

        # Stuff to do at closing time
        self._kill = None
        on_kill = kw.get('on_kill', [])
        # Check that all things to kill are callable:
        for t in on_kill:
            if not callable(t):
                raise TypeError, 'on_kill must be a list of callables'
        self.on_kill = on_kill
        # thread identity of the "worker thread" (that may execute code directly)
        self.worker_ident = None
        self.reactor_started = False
        self.first_run = True
Пример #2
0
    def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Modified version of code.py's runsource(), to handle threading issues.
        See the original for full docstring details."""

        # If Ctrl-C was typed, we reset the flag and return right away
        if shellglobals.KBINT:
            shellglobals.KBINT = False
            return False

        if self._kill:
            # can't queue new code if we are being killed
            return True

        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # shortcut - if we are in worker thread, or the worker thread is not running,
        # execute directly (to allow recursion and prevent deadlock if code is run early
        # in IPython construction)

        if (not self.reactor_started
                or (self.worker_ident is None and not self.first_run)
                or self.worker_ident == thread.get_ident()
                or shellglobals.run_in_frontend(source)):
            InteractiveShell.runcode(self, code)
            return

        # Case 3
        # Store code in queue, so the execution thread can handle it.

        self.first_run = False
        completed_ev, received_ev = threading.Event(), threading.Event()

        self.code_queue.put((code, completed_ev, received_ev))

        reactor.callLater(0.0, self.runcode)
        received_ev.wait(5)
        if not received_ev.isSet():
            # the mainloop is dead, start executing code directly
            print "Warning: Timeout for mainloop thread exceeded"
            print "switching to nonthreaded mode (until mainloop wakes up again)"
            self.worker_ident = None
        else:
            completed_ev.wait()

        return False
Пример #3
0
    def construct(self):
        # I am a little hesitant to put these into InteractiveShell itself.
        # But that might be the place for them
        sys.path.insert(0, '')

        # Create an InteractiveShell instance
        self.shell = InteractiveShell(
            parent=None,
            config=self.master_config
        )
Пример #4
0
    def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Modified version of code.py's runsource(), to handle threading issues.
        See the original for full docstring details."""
        
        # If Ctrl-C was typed, we reset the flag and return right away
        if shellglobals.KBINT:
            shellglobals.KBINT = False
            return False

        if self._kill:
            # can't queue new code if we are being killed
            return True
        
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # shortcut - if we are in worker thread, or the worker thread is not running, 
        # execute directly (to allow recursion and prevent deadlock if code is run early 
        # in IPython construction)
        
        if (not self.reactor_started or (self.worker_ident is None and not self.first_run) 
            or self.worker_ident == thread.get_ident() or shellglobals.run_in_frontend(source)):
            InteractiveShell.runcode(self,code)
            return

        # Case 3
        # Store code in queue, so the execution thread can handle it.
 
        self.first_run = False
        completed_ev, received_ev = threading.Event(), threading.Event() 
        
        self.code_queue.put((code,completed_ev, received_ev))

        reactor.callLater(0.0,self.runcode)
        received_ev.wait(5)
        if not received_ev.isSet():
            # the mainloop is dead, start executing code directly
            print "Warning: Timeout for mainloop thread exceeded"
            print "switching to nonthreaded mode (until mainloop wakes up again)"
            self.worker_ident = None
        else:            
            completed_ev.wait()
        
        return False
Пример #5
0
def prefilter_PQ(self,line,continuation):
    """Alternate prefilter for input of PhysicalQuantityInteractive objects.

    This assumes that the function PhysicalQuantityInteractive() has been
    imported."""

    from re import match
    from IPython.core.iplib import InteractiveShell

    # This regexp is what does the real work
    unit_split = match(r'\s*(\w+)\s*=\s*(-?\d*\.?\d*[eE]?-?\d*)\s+([a-zA-Z].*)',
                       line)

    # If special input was ecnountered, process it:
    if unit_split:
        var,val,units = unit_split.groups()
        if var and val and units:
            units = units.replace('^','**')
            # Now a valid line needs to be constructed for IPython to process:
            line = var +" = PhysicalQuantityInteractive(" + val + ", '" + \
                   units + "')"
            #print 'New line:',line   # dbg
            
    # In the end, always call the default IPython _prefilter() function.  Note
    # that self must be passed explicitly, b/c we're calling the unbound class
    # method (since this method will overwrite the instance prefilter())
    return InteractiveShell._prefilter(self,line,continuation)
Пример #6
0
 def __init__(self, session, reply_socket, pub_socket):
     self.session = session
     self.reply_socket = reply_socket
     self.pub_socket = pub_socket
     self.user_ns = {}
     self.history = []
     #self.Shell=InteractiveShell()
     self.compiler = InteractiveShell(user_ns=self.user_ns,user_global_ns=self.user_ns)
     self.compiler.init_alias()
     self.compiler.init_builtins()
     self.compiler.init_inspector()
     self.compiler.init_magics()
     self.compiler.init_pdb()
     self.compiler.init_sys_modules()
     self.compiler.init_instance_attrs()
     self.compiler.init_user_ns()
     
     
     
     
     #self.compiler = CommandCompiler()
     self.completer = KernelCompleter(self.user_ns)
     
     # Build dict of handlers for message types
     self.handlers = {}
     for msg_type in ['execute_request', 'complete_request']:
         self.handlers[msg_type] = getattr(self, msg_type)
def prefilter_PQ(self, line, continuation):
    """Alternate prefilter for input of PhysicalQuantityInteractive objects.

    This assumes that the function PhysicalQuantityInteractive() has been
    imported."""

    from re import match
    from IPython.core.iplib import InteractiveShell

    # This regexp is what does the real work
    unit_split = match(
        r'\s*(\w+)\s*=\s*(-?\d*\.?\d*[eE]?-?\d*)\s+([a-zA-Z].*)', line)

    # If special input was ecnountered, process it:
    if unit_split:
        var, val, units = unit_split.groups()
        if var and val and units:
            units = units.replace('^', '**')
            # Now a valid line needs to be constructed for IPython to process:
            line = var +" = PhysicalQuantityInteractive(" + val + ", '" + \
                   units + "')"
            #print 'New line:',line   # dbg

    # In the end, always call the default IPython _prefilter() function.  Note
    # that self must be passed explicitly, b/c we're calling the unbound class
    # method (since this method will overwrite the instance prefilter())
    return InteractiveShell._prefilter(self, line, continuation)
Пример #8
0
    def construct(self):
        # I am a little hesitant to put these into InteractiveShell itself.
        # But that might be the place for them
        sys.path.insert(0, '')

        # Create an InteractiveShell instance
        self.shell = InteractiveShell(None, self.master_config)
Пример #9
0
def get():
    """Get the most recently created InteractiveShell instance."""
    from IPython.core.iplib import InteractiveShell
    insts = InteractiveShell.get_instances()
    most_recent = insts[0]
    for inst in insts[1:]:
        if inst.created > most_recent.created:
            most_recent = inst
    return most_recent
Пример #10
0
   def __init__(self,filename="<ipython_frontent>", session = session, request_socket=None, subscribe_socket=None):
       InteractiveShell.__init__(self)
       self.buffer_lines=[]
       #self.display_banner = CBool(False)
       
       self.completer=completer.ClientCompleter(self,session,request_socket)
       self.Completer=self.completer
       self.handlers = {}
       for msg_type in ['pyin', 'pyout', 'pyerr', 'stream']:
           self.handlers[msg_type] = getattr(self, 'handle_%s' % msg_type)
       self.session = session
       self.request_socket = request_socket
       self.sub_socket = subscribe_socket
       self.backgrounded = 0
       self.messages = {}
       #setting clors on trecabacks
       sys.excepthook = ultratb.ColorTB()
#       sys.excepthook = ultratb.VerboseTB()
       self.formattedtb=ultratb.FormattedTB()
Пример #11
0
def get():
    """Get the most recently created InteractiveShell instance."""
    from IPython.core.iplib import InteractiveShell
    insts = InteractiveShell.get_instances()
    if len(insts)==0:
        return None
    most_recent = insts[0]
    for inst in insts[1:]:
        if inst.created > most_recent.created:
            most_recent = inst
    return most_recent
Пример #12
0
 def __init__(self,session, reply_socket, pub_socket):
     self.session = session
     self.reply_socket = reply_socket
     self.pub_socket = pub_socket
     self.user_ns = {}
     self.history = []
     InteractiveShell.__init__(self,user_ns=self.user_ns,user_global_ns=self.user_ns)
     
     #getting outputs
     self.stdout = OutStream(self.session, self.pub_socket, u'stdout')
     self.stderr = OutStream(self.session, self.pub_socket, u'stderr')
     sys.stdout = self.stdout
     sys.stderr = self.stderr
     self.InteractiveTB.out_stream=self.stderr
     self.display_hook=DisplayHook(self.session,self.pub_socket)
     #setting our own completer
     self.completer=KernelCompleter(self,self.user_ns)
     self.handlers = {}
     for msg_type in ['execute_request', 'complete_request']:
         self.handlers[msg_type] = getattr(self, msg_type)
Пример #13
0
    def __init__(self, ipython0=None, *args, **kwargs):
        """ Parameters
            ----------

            ipython0: an optional ipython0 instance to use for command
            prefiltering and completion.
        """
        LineFrontEndBase.__init__(self, *args, **kwargs)
        self.shell.output_trap = RedirectorOutputTrap(
            out_callback=self.write,
            err_callback=self.write,
        )
        self.shell.traceback_trap = SyncTracebackTrap(
            formatters=self.shell.traceback_trap.formatters, )

        # Start the ipython0 instance:
        self.save_output_hooks()
        if ipython0 is None:
            # Instanciate an IPython0 InteractiveShell to be able to use the
            # prefiltering.
            # Suppress all key input, to avoid waiting
            def my_rawinput(x=None):
                return '\n'

            old_rawinput = __builtin__.raw_input
            __builtin__.raw_input = my_rawinput
            ipython0 = InteractiveShell(
                parent=None,
                user_ns=self.shell.user_ns,
                user_global_ns=self.shell.user_global_ns)
            __builtin__.raw_input = old_rawinput
        self.ipython0 = ipython0
        # Set the pager:
        self.ipython0.set_hook('show_in_pager',
                               lambda s, string: self.write("\n" + string))
        self.ipython0.write = self.write
        self._ip = _ip = self.ipython0
        # Make sure the raw system call doesn't get called, as we don't
        # have a stdin accessible.
        self._ip.system = self.system_call
        # XXX: Muck around with magics so that they work better
        # in our environment
        if not sys.platform.startswith('win'):
            self.ipython0.magic_ls = mk_system_call(self.system_call, 'ls -CF')
        # And now clean up the mess created by ipython0
        self.release_output()

        if not 'banner' in kwargs and self.banner is None:
            self.banner = self.ipython0.banner

        # FIXME: __init__ and start should be two different steps
        self.start()
Пример #14
0
    def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
                 user_ns=None,user_global_ns=None,banner2='',**kw):
        """Similar to the normal InteractiveShell, but with threading control"""
        
        InteractiveShell.__init__(self,name,usage,rc,user_ns,
                                  user_global_ns,banner2)


        # A queue to hold the code to be executed. 
        self.code_queue = Queue.Queue()

        # Stuff to do at closing time
        self._kill = None
        on_kill = kw.get('on_kill', [])
        # Check that all things to kill are callable:
        for t in on_kill:
            if not callable(t):
                raise TypeError,'on_kill must be a list of callables'
        self.on_kill = on_kill
        # thread identity of the "worker thread" (that may execute code directly)
        self.worker_ident = None
        self.reactor_started = False
        self.first_run = True
Пример #15
0
# Deprecated way to handle special types
# These are going away in 1.4
from h5t import py_new_vlen as new_vlen
from h5t import py_get_vlen as get_vlen
from h5t import py_new_enum as new_enum
from h5t import py_get_enum as get_enum

__doc__ = __doc__ % (version.version, version.hdf5_version,
                     version.api_version)

__all__ = [
    'h5', 'h5f', 'h5g', 'h5s', 'h5t', 'h5d', 'h5a', 'h5p', 'h5r', 'h5o', 'h5l',
    'h5z', 'h5i', 'version', 'File', 'Group', 'Dataset', 'Datatype',
    'AttributeManager', 'H5Error', 'get_config', 'is_hdf5', 'special_dtype',
    'check_dtype', 'SoftLink', 'ExternalLink'
]

try:
    try:
        from IPython.core.iplib import InteractiveShell
        ip_running = InteractiveShell.initialized()
    except ImportError:
        # support <ipython-0.11
        from IPython import ipapi
        ip_running = ipapi.get() is not None
    if ip_running:
        import _ipy_completer
        _ipy_completer.activate()
except Exception:
    pass
Пример #16
0
class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list + (
        make_option('--ipython',
                    action='store_true',
                    dest='ipython',
                    help='Tells Django to use IPython, not BPython.'),
        make_option(
            '--plain',
            action='store_true',
            dest='plain',
            help='Tells Django to use plain Python, not BPython nor IPython.'),
        make_option('--no-pythonrc',
                    action='store_true',
                    dest='no_pythonrc',
                    help='Tells Django to use plain Python, not IPython.'),
        make_option('--print-sql',
                    action='store_true',
                    default=False,
                    help="Print SQL queries as they're executed"),
    )
    help = "Like the 'shell' command but autoloads the models of all installed Django apps."

    requires_model_validation = True

    def handle_noargs(self, **options):
        # XXX: (Temporary) workaround for ticket #1796: force early loading of all
        # models from installed apps. (this is fixed by now, but leaving it here
        # for people using 0.96 or older trunk (pre [5919]) versions.
        from django.db.models.loading import get_models, get_apps
        loaded_models = get_models()

        use_ipython = options.get('ipython', False)
        use_plain = options.get('plain', False)
        use_pythonrc = not options.get('no_pythonrc', True)

        if options.get("print_sql", False):
            # Code from http://gist.github.com/118990
            from django.db.backends import util
            try:
                import sqlparse
            except ImportError:
                sqlparse = None

            class PrintQueryWrapper(util.CursorDebugWrapper):
                def execute(self, sql, params=()):
                    try:
                        return self.cursor.execute(sql, params)
                    finally:
                        raw_sql = self.db.ops.last_executed_query(
                            self.cursor, sql, params)
                        if sqlparse:
                            print sqlparse.format(raw_sql, reindent=True)
                        else:
                            print raw_sql
                        print

            util.CursorDebugWrapper = PrintQueryWrapper

        # Set up a dictionary to serve as the environment for the shell, so
        # that tab completion works on objects that are imported at runtime.
        # See ticket 5082.
        from django.conf import settings
        imported_objects = {'settings': settings}
        for app_mod in get_apps():
            app_models = get_models(app_mod)
            if not app_models:
                continue
            model_labels = ", ".join([model.__name__ for model in app_models])
            print self.style.SQL_COLTYPE(
                "From '%s' autoload: %s" %
                (app_mod.__name__.split('.')[-2], model_labels))
            for model in app_models:
                try:
                    imported_objects[model.__name__] = getattr(
                        __import__(app_mod.__name__, {}, {}, model.__name__),
                        model.__name__)
                except AttributeError, e:
                    print self.style.ERROR(
                        "Failed to import '%s' from '%s' reason: %s" %
                        (model.__name__, app_mod.__name__.split('.')[-2],
                         str(e)))
                    continue
        try:
            if use_plain:
                # Don't bother loading B/IPython, because the user wants plain Python.
                raise ImportError
            try:
                if use_ipython:
                    # User wants IPython
                    raise ImportError
                from bpython import embed
                embed(imported_objects)
            except ImportError:
                # Explicitly pass an empty list as arguments, because otherwise IPython
                # would use sys.argv from this script.
                try:
                    from IPython.core.iplib import InteractiveShell
                    shell = InteractiveShell(user_ns=imported_objects)
                except ImportError:
                    import IPython
                    shell = IPython.Shell.IPShell(argv=[],
                                                  user_ns=imported_objects)
                shell.mainloop()
        except ImportError:
            # Using normal Python shell
            import code
            try:  # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(
                    rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
            # conventions and get $PYTHONSTARTUP first then import user.
            if use_pythonrc:
                pythonrc = os.environ.get("PYTHONSTARTUP")
                if pythonrc and os.path.isfile(pythonrc):
                    try:
                        execfile(pythonrc)
                    except NameError:
                        pass
                # This will import .pythonrc.py as a side-effect
                import user
            code.interact(local=imported_objects)
Пример #17
0
class Kernel(object):

    def __init__(self, session, reply_socket, pub_socket):
        self.session = session
        self.reply_socket = reply_socket
        self.pub_socket = pub_socket
        self.user_ns = {}
        self.history = []
        #self.Shell=InteractiveShell()
        self.compiler = InteractiveShell(user_ns=self.user_ns,user_global_ns=self.user_ns)
        self.compiler.init_alias()
        self.compiler.init_builtins()
        self.compiler.init_inspector()
        self.compiler.init_magics()
        self.compiler.init_pdb()
        self.compiler.init_sys_modules()
        self.compiler.init_instance_attrs()
        self.compiler.init_user_ns()
        
        
        
        
        #self.compiler = CommandCompiler()
        self.completer = KernelCompleter(self.user_ns)
        
        # Build dict of handlers for message types
        self.handlers = {}
        for msg_type in ['execute_request', 'complete_request']:
            self.handlers[msg_type] = getattr(self, msg_type)

    def abort_queue(self):
        while True:
            try:
                ident = self.reply_socket.recv(zmq.NOBLOCK)
            except zmq.ZMQError, e:
                if e.errno == zmq.EAGAIN:
                    break
            else:
                assert self.reply_socket.rcvmore(), "Unexpected missing message part."
                msg = self.reply_socket.recv_json()
            print>>sys.__stdout__, "Aborting:"
            print>>sys.__stdout__, Message(msg)
            msg_type = msg['msg_type']
            reply_type = msg_type.split('_')[0] + '_reply'
            reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
            print>>sys.__stdout__, Message(reply_msg)
            self.reply_socket.send(ident,zmq.SNDMORE)
            self.reply_socket.send_json(reply_msg)
            # We need to wait a bit for requests to come in. This can probably
            # be set shorter for true asynchronous clients.
            time.sleep(0.1)
Пример #18
0
# Deprecated way to handle special types
# These are going away in 1.4
from h5t import py_new_vlen as new_vlen
from h5t import py_get_vlen as get_vlen
from h5t import py_new_enum as new_enum
from h5t import py_get_enum as get_enum

__doc__ = __doc__ % (version.version, version.hdf5_version, version.api_version)

__all__ = ['h5', 'h5f', 'h5g', 'h5s', 'h5t', 'h5d', 'h5a', 'h5p', 'h5r',
           'h5o', 'h5l', 'h5z', 'h5i', 'version', 'File', 'Group', 'Dataset',
           'Datatype', 'AttributeManager', 'H5Error', 'get_config', 'is_hdf5',
           'special_dtype', 'check_dtype', 'SoftLink', 'ExternalLink']

try:
    try:
        from IPython.core.iplib import InteractiveShell
        ip_running = InteractiveShell.initialized()
    except ImportError:
        # support <ipython-0.11
        from IPython import ipapi
        ip_running = ipapi.get() is not None
    if ip_running:
        import _ipy_completer
        _ipy_completer.activate()
except Exception:
    pass


Пример #19
0
class IPythonApp(Application):
    name = 'ipython'
    config_file_name = _default_config_file_name

    def create_default_config(self):
        super(IPythonApp, self).create_default_config()
        self.default_config.Global.display_banner = True
        
        # If the -c flag is given or a file is given to run at the cmd line
        # like "ipython foo.py", normally we exit without starting the main
        # loop.  The force_interact config variable allows a user to override
        # this and interact.  It is also set by the -i cmd line flag, just
        # like Python.
        self.default_config.Global.force_interact = False

        # By default always interact by starting the IPython mainloop.
        self.default_config.Global.interact = True

        # Let the parent class set the default, but each time log_level
        # changes from config, we need to update self.log_level as that is
        # what updates the actual log level in self.log.
        self.default_config.Global.log_level = self.log_level

        # No GUI integration by default
        self.default_config.Global.wthread = False
        self.default_config.Global.q4thread = False
        self.default_config.Global.gthread = False

    def create_command_line_config(self):
        """Create and return a command line config loader."""
        return IPythonAppCLConfigLoader(
            description=ipython_desc,
            version=release.version)

    def post_load_command_line_config(self):
        """Do actions after loading cl config."""
        clc = self.command_line_config

        # Display the deprecation warnings about threaded shells
        if hasattr(clc.Global, 'pylab'):
            pylab_warning()
            del clc.Global['pylab']

    def load_file_config(self):
        if hasattr(self.command_line_config.Global, 'quick'):
            if self.command_line_config.Global.quick:
                self.file_config = Config()
                return
        super(IPythonApp, self).load_file_config()

    def post_load_file_config(self):
        if hasattr(self.command_line_config.Global, 'extra_extension'):
            if not hasattr(self.file_config.Global, 'extensions'):
                self.file_config.Global.extensions = []
            self.file_config.Global.extensions.append(
                self.command_line_config.Global.extra_extension)
            del self.command_line_config.Global.extra_extension

    def pre_construct(self):
        config = self.master_config

        if hasattr(config.Global, 'classic'):
            if config.Global.classic:
                config.InteractiveShell.cache_size = 0
                config.InteractiveShell.pprint = 0
                config.InteractiveShell.prompt_in1 = '>>> '
                config.InteractiveShell.prompt_in2 = '... '
                config.InteractiveShell.prompt_out = ''
                config.InteractiveShell.separate_in = \
                    config.InteractiveShell.separate_out = \
                    config.InteractiveShell.separate_out2 = ''
                config.InteractiveShell.colors = 'NoColor'
                config.InteractiveShell.xmode = 'Plain'

        if hasattr(config.Global, 'nosep'):
            if config.Global.nosep:
                config.InteractiveShell.separate_in = \
                config.InteractiveShell.separate_out = \
                config.InteractiveShell.separate_out2 = ''

        # if there is code of files to run from the cmd line, don't interact
        # unless the -i flag (Global.force_interact) is true.
        code_to_run = config.Global.get('code_to_run','')
        file_to_run = False
        if len(self.extra_args)>=1:
            if self.extra_args[0]:
                file_to_run = True
        if file_to_run or code_to_run:
            if not config.Global.force_interact:
                config.Global.interact = False

    def construct(self):
        # I am a little hesitant to put these into InteractiveShell itself.
        # But that might be the place for them
        sys.path.insert(0, '')

        # Create an InteractiveShell instance
        self.shell = InteractiveShell(
            parent=None,
            config=self.master_config
        )

    def post_construct(self):
        """Do actions after construct, but before starting the app."""
        config = self.master_config
        
        # shell.display_banner should always be False for the terminal 
        # based app, because we call shell.show_banner() by hand below
        # so the banner shows *before* all extension loading stuff.
        self.shell.display_banner = False

        if config.Global.display_banner and \
            config.Global.interact:
            self.shell.show_banner()

        # Make sure there is a space below the banner.
        if self.log_level <= logging.INFO: print

        # Now a variety of things that happen after the banner is printed.
        self._enable_gui()
        self._load_extensions()
        self._run_exec_lines()
        self._run_exec_files()
        self._run_cmd_line_code()

    def _enable_gui(self):
        """Enable GUI event loop integration."""
        config = self.master_config
        try:
            # Enable GUI integration
            if config.Global.wthread:
                self.log.info("Enabling wx GUI event loop integration")
                inputhook.enable_wx(app=True)
            elif config.Global.q4thread:
                self.log.info("Enabling Qt4 GUI event loop integration")
                inputhook.enable_qt4(app=True)
            elif config.Global.gthread:
                self.log.info("Enabling GTK GUI event loop integration")
                inputhook.enable_gtk(app=True)
        except:
            self.log.warn("Error in enabling GUI event loop integration:")
            self.shell.showtraceback()

    def _load_extensions(self):
        """Load all IPython extensions in Global.extensions.

        This uses the :meth:`InteractiveShell.load_extensions` to load all
        the extensions listed in ``self.master_config.Global.extensions``.
        """
        try:
            if hasattr(self.master_config.Global, 'extensions'):
                self.log.debug("Loading IPython extensions...")
                extensions = self.master_config.Global.extensions
                for ext in extensions:
                    try:
                        self.log.info("Loading IPython extension: %s" % ext)                        
                        self.shell.load_extension(ext)
                    except:
                        self.log.warn("Error in loading extension: %s" % ext)
                        self.shell.showtraceback()
        except:
            self.log.warn("Unknown error in loading extensions:")
            self.shell.showtraceback()

    def _run_exec_lines(self):
        """Run lines of code in Global.exec_lines in the user's namespace."""
        try:
            if hasattr(self.master_config.Global, 'exec_lines'):
                self.log.debug("Running code from Global.exec_lines...")
                exec_lines = self.master_config.Global.exec_lines
                for line in exec_lines:
                    try:
                        self.log.info("Running code in user namespace: %s" % line)
                        self.shell.runlines(line)
                    except:
                        self.log.warn("Error in executing line in user namespace: %s" % line)
                        self.shell.showtraceback()
        except:
            self.log.warn("Unknown error in handling Global.exec_lines:")
            self.shell.showtraceback()

    def _exec_file(self, fname):
        full_filename = filefind(fname, ['.', self.ipythondir])
        if os.path.isfile(full_filename):
            if full_filename.endswith('.py'):
                self.log.info("Running file in user namespace: %s" % full_filename)
                self.shell.safe_execfile(full_filename, self.shell.user_ns)
            elif full_filename.endswith('.ipy'):
                self.log.info("Running file in user namespace: %s" % full_filename)
                self.shell.safe_execfile_ipy(full_filename)
            else:
                self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)

    def _run_exec_files(self):
        try:
            if hasattr(self.master_config.Global, 'exec_files'):
                self.log.debug("Running files in Global.exec_files...")
                exec_files = self.master_config.Global.exec_files
                for fname in exec_files:
                    self._exec_file(fname)
        except:
            self.log.warn("Unknown error in handling Global.exec_files:")
            self.shell.showtraceback()

    def _run_cmd_line_code(self):
        if hasattr(self.master_config.Global, 'code_to_run'):
            line = self.master_config.Global.code_to_run
            try:
                self.log.info("Running code given at command line (-c): %s" % line)
                self.shell.runlines(line)
            except:
                self.log.warn("Error in executing line in user namespace: %s" % line)
                self.shell.showtraceback()
            return
        # Like Python itself, ignore the second if the first of these is present
        try:
            fname = self.extra_args[0]
        except:
            pass
        else:
            try:
                self._exec_file(fname)
            except:
                self.log.warn("Error in executing file in user namespace: %s" % fname)
                self.shell.showtraceback()

    def start_app(self):
        if self.master_config.Global.interact:
            self.log.debug("Starting IPython's mainloop...")
            self.shell.mainloop()
Пример #20
0
    def runcode(self):
        """Execute a code object.

        Multithreaded wrapper around IPython's runcode()."""

        # we are in worker thread, stash out the id for runsource()
        self.worker_ident = thread.get_ident()

        if self._kill:
            print >> Term.cout, 'Closing threads...',
            Term.cout.flush()
            for tokill in self.on_kill:
                tokill()
            print >> Term.cout, 'Done.'
            # allow kill() to return
            self._kill.set()
            return True

        # Install SIGINT handler.  We do it every time to ensure that if user
        # code modifies it, we restore our own handling.
        try:
            pass
            signal(SIGINT, shellglobals.sigint_handler)
        except SystemError:
            # This happens under Windows, which seems to have all sorts
            # of problems with signal handling.  Oh well...
            pass

        # Flush queue of pending code by calling the run methood of the parent
        # class with all items which may be in the queue.
        code_to_run = None
        while 1:
            try:
                code_to_run, completed_ev, received_ev = self.code_queue.get_nowait(
                )
            except Queue.Empty:
                break
            received_ev.set()

            # Exceptions need to be raised differently depending on which
            # thread is active.  This convoluted try/except is only there to
            # protect against asynchronous exceptions, to ensure that a shellglobals.KBINT
            # at the wrong time doesn't deadlock everything.  The global
            # CODE_TO_RUN is set to true/false as close as possible to the
            # runcode() call, so that the KBINT handler is correctly informed.
            try:
                try:
                    shellglobals.CODE_RUN = True
                    InteractiveShell.runcode(self, code_to_run)
                except KeyboardInterrupt:
                    print "Keyboard interrupted in mainloop"
                    while not self.code_queue.empty():
                        code = self.code_queue.get_nowait()
                    break
            finally:
                shellglobals.CODE_RUN = False
                # allow runsource() return from wait
                completed_ev.set()

        # This MUST return true for gtk threading to work
        return True
Пример #21
0
    def runcode(self):
        """Execute a code object.

        Multithreaded wrapper around IPython's runcode()."""
        
        
        # we are in worker thread, stash out the id for runsource() 
        self.worker_ident = thread.get_ident()

        if self._kill:
            print >>Term.cout, 'Closing threads...',
            Term.cout.flush()
            for tokill in self.on_kill:
                tokill()
            print >>Term.cout, 'Done.'
            # allow kill() to return
            self._kill.set()
            return True

        # Install SIGINT handler.  We do it every time to ensure that if user
        # code modifies it, we restore our own handling.
        try:
            pass
            signal(SIGINT,shellglobals.sigint_handler)
        except SystemError:
            # This happens under Windows, which seems to have all sorts
            # of problems with signal handling.  Oh well...
            pass

        # Flush queue of pending code by calling the run methood of the parent
        # class with all items which may be in the queue.
        code_to_run = None
        while 1:
            try:
                code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()                
            except Queue.Empty:
                break
            received_ev.set()

            
            # Exceptions need to be raised differently depending on which
            # thread is active.  This convoluted try/except is only there to
            # protect against asynchronous exceptions, to ensure that a shellglobals.KBINT
            # at the wrong time doesn't deadlock everything.  The global
            # CODE_TO_RUN is set to true/false as close as possible to the
            # runcode() call, so that the KBINT handler is correctly informed.
            try:
                try:
                   shellglobals.CODE_RUN = True
                   InteractiveShell.runcode(self,code_to_run)
                except KeyboardInterrupt:
                   print "Keyboard interrupted in mainloop"
                   while not self.code_queue.empty():
                      code = self.code_queue.get_nowait()
                   break
            finally:
                shellglobals.CODE_RUN = False
                # allow runsource() return from wait
                completed_ev.set()                
        
        # This MUST return true for gtk threading to work
        return True
Пример #22
0
class IPythonApp(Application):
    name = u'ipython'
    #: argparse formats better the 'usage' than the 'description' field
    description = None
    usage = usage.cl_usage
    command_line_loader = IPAppConfigLoader
    default_config_file_name = default_config_file_name
    crash_handler_class = IPAppCrashHandler

    def create_default_config(self):
        super(IPythonApp, self).create_default_config()
        # Eliminate multiple lookups
        Global = self.default_config.Global

        # Set all default values
        Global.display_banner = True
        
        # If the -c flag is given or a file is given to run at the cmd line
        # like "ipython foo.py", normally we exit without starting the main
        # loop.  The force_interact config variable allows a user to override
        # this and interact.  It is also set by the -i cmd line flag, just
        # like Python.
        Global.force_interact = False

        # By default always interact by starting the IPython mainloop.
        Global.interact = True

        # No GUI integration by default
        Global.gui = False
        # Pylab off by default
        Global.pylab = False

        # Deprecated versions of gui support that used threading, we support
        # them just for bacwards compatibility as an alternate spelling for
        # '--gui X'
        Global.qthread = False
        Global.q4thread = False
        Global.wthread = False
        Global.gthread = False

    def load_file_config(self):
        if hasattr(self.command_line_config.Global, 'quick'):
            if self.command_line_config.Global.quick:
                self.file_config = Config()
                return
        super(IPythonApp, self).load_file_config()

    def post_load_file_config(self):
        if hasattr(self.command_line_config.Global, 'extra_extension'):
            if not hasattr(self.file_config.Global, 'extensions'):
                self.file_config.Global.extensions = []
            self.file_config.Global.extensions.append(
                self.command_line_config.Global.extra_extension)
            del self.command_line_config.Global.extra_extension

    def pre_construct(self):
        config = self.master_config

        if hasattr(config.Global, 'classic'):
            if config.Global.classic:
                config.InteractiveShell.cache_size = 0
                config.InteractiveShell.pprint = 0
                config.InteractiveShell.prompt_in1 = '>>> '
                config.InteractiveShell.prompt_in2 = '... '
                config.InteractiveShell.prompt_out = ''
                config.InteractiveShell.separate_in = \
                    config.InteractiveShell.separate_out = \
                    config.InteractiveShell.separate_out2 = ''
                config.InteractiveShell.colors = 'NoColor'
                config.InteractiveShell.xmode = 'Plain'

        if hasattr(config.Global, 'nosep'):
            if config.Global.nosep:
                config.InteractiveShell.separate_in = \
                config.InteractiveShell.separate_out = \
                config.InteractiveShell.separate_out2 = ''

        # if there is code of files to run from the cmd line, don't interact
        # unless the -i flag (Global.force_interact) is true.
        code_to_run = config.Global.get('code_to_run','')
        file_to_run = False
        if self.extra_args and self.extra_args[0]:
                file_to_run = True
        if file_to_run or code_to_run:
            if not config.Global.force_interact:
                config.Global.interact = False

    def construct(self):
        # I am a little hesitant to put these into InteractiveShell itself.
        # But that might be the place for them
        sys.path.insert(0, '')

        # Create an InteractiveShell instance
        self.shell = InteractiveShell(None, self.master_config)

    def post_construct(self):
        """Do actions after construct, but before starting the app."""
        config = self.master_config
        
        # shell.display_banner should always be False for the terminal 
        # based app, because we call shell.show_banner() by hand below
        # so the banner shows *before* all extension loading stuff.
        self.shell.display_banner = False
        if config.Global.display_banner and \
            config.Global.interact:
            self.shell.show_banner()

        # Make sure there is a space below the banner.
        if self.log_level <= logging.INFO: print

        # Now a variety of things that happen after the banner is printed.
        self._enable_gui_pylab()
        self._load_extensions()
        self._run_exec_lines()
        self._run_exec_files()
        self._run_cmd_line_code()

    def _enable_gui_pylab(self):
        """Enable GUI event loop integration, taking pylab into account."""
        Global = self.master_config.Global

        # Select which gui to use
        if Global.gui:
            gui = Global.gui
        # The following are deprecated, but there's likely to be a lot of use
        # of this form out there, so we might as well support it for now.  But
        # the --gui option above takes precedence.
        elif Global.wthread:
            gui = inputhook.GUI_WX
        elif Global.qthread:
            gui = inputhook.GUI_QT
        elif Global.gthread:
            gui = inputhook.GUI_GTK
        else:
            gui = None

        # Using --pylab will also require gui activation, though which toolkit
        # to use may be chosen automatically based on mpl configuration.
        if Global.pylab:
            activate = self.shell.enable_pylab
            if Global.pylab == 'auto':
                gui = None
            else:
                gui = Global.pylab
        else:
            # Enable only GUI integration, no pylab
            activate = inputhook.enable_gui

        if gui or Global.pylab:
            try:
                self.log.info("Enabling GUI event loop integration, "
                              "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
                activate(gui)
            except:
                self.log.warn("Error in enabling GUI event loop integration:")
                self.shell.showtraceback()

    def _load_extensions(self):
        """Load all IPython extensions in Global.extensions.

        This uses the :meth:`InteractiveShell.load_extensions` to load all
        the extensions listed in ``self.master_config.Global.extensions``.
        """
        try:
            if hasattr(self.master_config.Global, 'extensions'):
                self.log.debug("Loading IPython extensions...")
                extensions = self.master_config.Global.extensions
                for ext in extensions:
                    try:
                        self.log.info("Loading IPython extension: %s" % ext)                        
                        self.shell.load_extension(ext)
                    except:
                        self.log.warn("Error in loading extension: %s" % ext)
                        self.shell.showtraceback()
        except:
            self.log.warn("Unknown error in loading extensions:")
            self.shell.showtraceback()

    def _run_exec_lines(self):
        """Run lines of code in Global.exec_lines in the user's namespace."""
        try:
            if hasattr(self.master_config.Global, 'exec_lines'):
                self.log.debug("Running code from Global.exec_lines...")
                exec_lines = self.master_config.Global.exec_lines
                for line in exec_lines:
                    try:
                        self.log.info("Running code in user namespace: %s" %
                                      line)
                        self.shell.runlines(line)
                    except:
                        self.log.warn("Error in executing line in user "
                                      "namespace: %s" % line)
                        self.shell.showtraceback()
        except:
            self.log.warn("Unknown error in handling Global.exec_lines:")
            self.shell.showtraceback()

    def _exec_file(self, fname):
        full_filename = filefind(fname, [u'.', self.ipython_dir])
        if os.path.isfile(full_filename):
            if full_filename.endswith(u'.py'):
                self.log.info("Running file in user namespace: %s" %
                              full_filename)
                # Ensure that __file__ is always defined to match Python behavior
                self.shell.user_ns['__file__'] = fname
                try:
                    self.shell.safe_execfile(full_filename, self.shell.user_ns)
                finally:
                    del self.shell.user_ns['__file__']
            elif full_filename.endswith('.ipy'):
                self.log.info("Running file in user namespace: %s" %
                              full_filename)
                self.shell.safe_execfile_ipy(full_filename)
            else:
                self.log.warn("File does not have a .py or .ipy extension: <%s>"
                               % full_filename)
    def _run_exec_files(self):
        try:
            if hasattr(self.master_config.Global, 'exec_files'):
                self.log.debug("Running files in Global.exec_files...")
                exec_files = self.master_config.Global.exec_files
                for fname in exec_files:
                    self._exec_file(fname)
        except:
            self.log.warn("Unknown error in handling Global.exec_files:")
            self.shell.showtraceback()

    def _run_cmd_line_code(self):
        if hasattr(self.master_config.Global, 'code_to_run'):
            line = self.master_config.Global.code_to_run
            try:
                self.log.info("Running code given at command line (-c): %s" %
                              line)
                self.shell.runlines(line)
            except:
                self.log.warn("Error in executing line in user namespace: %s" %
                              line)
                self.shell.showtraceback()
            return
        # Like Python itself, ignore the second if the first of these is present
        try:
            fname = self.extra_args[0]
        except:
            pass
        else:
            try:
                self._exec_file(fname)
            except:
                self.log.warn("Error in executing file in user namespace: %s" %
                              fname)
                self.shell.showtraceback()

    def start_app(self):
        if self.master_config.Global.interact:
            self.log.debug("Starting IPython's mainloop...")
            self.shell.mainloop()
        else:
            self.log.debug("IPython not interactive, start_app is no-op...")