[pytango] 51/483: added support for ipython 0.11

Sandor Bodo-Merle sbodomerle-guest at moszumanska.debian.org
Thu Sep 28 19:14:23 UTC 2017


This is an automated email from the git hooks/post-receive script.

sbodomerle-guest pushed a commit to annotated tag bliss_8.10
in repository pytango.

commit df6be9fc4e8b92fb4eb702bf3b1a0f8b3e162165
Author: tiagocoutinho <tiagocoutinho at 4e9c00fd-8f2e-0410-aa12-93ce3db5e235>
Date:   Fri Nov 4 16:56:47 2011 +0000

    added support for ipython 0.11
    
    git-svn-id: http://svn.code.sf.net/p/tango-cs/code/bindings/PyTango/trunk@18291 4e9c00fd-8f2e-0410-aa12-93ce3db5e235
---
 PyTango/ipython/__init__.py                    |   2 +
 PyTango/ipython/ipython.py                     |  37 +++--
 PyTango/ipython/ipython_00_11/__init__.py      |   3 +-
 PyTango/ipython/ipython_00_11/ipy_install.py   |  75 ++++-----
 PyTango/ipython/ipython_00_11/ipython_00_11.py | 205 +++++++++++++++++--------
 5 files changed, 208 insertions(+), 114 deletions(-)

diff --git a/PyTango/ipython/__init__.py b/PyTango/ipython/__init__.py
index 8988752..e7ba900 100644
--- a/PyTango/ipython/__init__.py
+++ b/PyTango/ipython/__init__.py
@@ -22,3 +22,5 @@
 ################################################################################
 
 from ipython import init_ipython, install
+from ipython import load_ipython_extension, unload_ipython_extension, \
+    init_ipython, load_config
diff --git a/PyTango/ipython/ipython.py b/PyTango/ipython/ipython.py
index 2645251..faaffba 100644
--- a/PyTango/ipython/ipython.py
+++ b/PyTango/ipython/ipython.py
@@ -21,7 +21,8 @@
 ##
 ################################################################################
 
-__all__ = ["init_ipython", "install"]
+__all__ = ["init_ipython", "install", "load_ipython_extension",
+           "unload_ipython_extension", "load_config"]
 
 import os
 
@@ -72,19 +73,25 @@ def default_init_ipython(ip, store=True, pytango=True, colors=True,
 def default_install(ipydir=None, verbose=True):
     print "Unsupported IPython version (%s) for spock profile" \
         % get_ipython_version()
-    print "Supported IPython versions are: 0.10"
+    print "Supported IPython versions are: 0.10, 0.11 and 0.12"
     print "Tango extension to IPyhon will NOT be installed."
-    
-def __define():
-    ipv = get_ipython_version_list()
-    ret = default_init_ipython, default_install
-    if ipv >= [0, 10] and ipv < [0, 11]:
-        import ipython_00_10
-        ret = ipython_00_10.init_ipython, ipython_00_10.install
-    elif ipv >= [0, 11] and ipv <= [0, 12]:
-        import ipython_00_11
-        ret = ipython_00_11.init_ipython, ipython_00_11.install        
-    return ret
-    
-init_ipython, install = __define()
+ 
+init_ipython = default_init_ipython
+install = default_install
 
+ipv = get_ipython_version_list()
+if ipv >= [0, 10] and ipv < [0, 11]:
+    import ipython_00_10
+    init_ipython = ipython_00_10.init_ipython
+    install = ipython_00_10.install
+    load_config = None
+    load_ipython_extension = None
+    unload_ipython_extension = None
+elif ipv >= [0, 11] and ipv <= [0, 12]:
+    import ipython_00_11
+    init_ipython = None
+    install = ipython_00_11.install
+    load_config = ipython_00_11.load_config
+    load_ipython_extension = ipython_00_11.load_ipython_extension
+    unload_ipython_extension = ipython_00_11.unload_ipython_extension
+    
\ No newline at end of file
diff --git a/PyTango/ipython/ipython_00_11/__init__.py b/PyTango/ipython/ipython_00_11/__init__.py
index 2ad2bbe..0481dde 100644
--- a/PyTango/ipython/ipython_00_11/__init__.py
+++ b/PyTango/ipython/ipython_00_11/__init__.py
@@ -21,5 +21,6 @@
 ##
 ################################################################################
 
-from ipython_00_11 import init_ipython
+from ipython_00_11 import load_ipython_extension, unload_ipython_extension, \
+    load_config
 from ipy_install import install
\ No newline at end of file
diff --git a/PyTango/ipython/ipython_00_11/ipy_install.py b/PyTango/ipython/ipython_00_11/ipy_install.py
index 97630e4..1bee65e 100644
--- a/PyTango/ipython/ipython_00_11/ipy_install.py
+++ b/PyTango/ipython/ipython_00_11/ipy_install.py
@@ -23,11 +23,18 @@
 ##
 ################################################################################
 
+from __future__ import with_statement
+
 import sys
 import os
 import StringIO
 
 import IPython
+from IPython.core.profiledir import ProfileDirError, ProfileDir
+from IPython.core.application import BaseIPythonApplication
+from IPython.utils.path import get_ipython_dir
+from IPython.utils.io import ask_yes_no
+
 import PyTango
 
 __PROFILE = """\
@@ -36,62 +43,56 @@ __PROFILE = """\
 friendly interface to Tango.
 Created with PyTango {pytangover} for IPython {ipyver}\"\"\"
 
-PyTango.ipython.init_ipython()
+import PyTango.ipython
+
+config = get_config()
+PyTango.ipython.load_config(config)
+
+# Put any additional environment here
 """
 
-def install(ipydir=None,verbose=True):
-    install_dir = ipydir or IPython.core.path.get_ipython_dir()
-    f_name = os.path.join(install_dir, 'ipy_profile_spock.py')
+def install(ipydir=None, verbose=True, profile='spock'):
     if verbose:
         out = sys.stdout
     else:
         out = StringIO.StringIO()
-    if ipydir is None and os.path.isfile(f_name):
-        print "Warning: The file '%s' already exists." % f_name
-        r = ''
-        while r.lower() not in ('y', 'n'):
-            r = raw_input("Do you wish to override it [Y/n]?")
-            r = r or 'y'
-        if r.lower() == 'n':
-            return
-    profile = __PROFILE.format(pytangover=PyTango.Release.version,
-                               ipyver=IPython.release.version)
     
+    ipython_dir = ipydir or get_ipython_dir()
+    try:
+        p_dir = ProfileDir.find_profile_dir_by_name(ipython_dir, profile)
+    except ProfileDirError:
+        p_dir = ProfileDir.create_profile_dir_by_name(ipython_dir, profile)
+    
+    config_file_name = BaseIPythonApplication.config_file_name.default_value
+    abs_config_file_name = os.path.join(p_dir.location, config_file_name)
+    create_config = True
+    if os.path.isfile(abs_config_file_name):
+        create_config = ask_yes_no("Spock configuration file already exists. "\
+                                   "Do you wish to replace it?", default='y')
+    
+    if not create_config:
+        return
+
     out.write("Installing spock extension to ipython... ")
     out.flush()
-    try:
-        f = file(f_name, "w")
+
+    profile = __PROFILE.format(pytangover=PyTango.Release.version,
+                               ipyver=IPython.release.version)
+    with file(abs_config_file_name, "w") as f:
         f.write(profile)
         f.close()
-        out.write("[DONE]\n\n")
-    except Exception, e:
-        out.write("[FAILED]\n\n")
-        raise e
-    
-    d = IPython.core.path.get_ipython_dir()
-    ipy_user_config = os.path.join(d, 'ipy_user_conf.py')
+    out.write("[DONE]\n\n")
     out.write("""\
 To start spock simply type on the command line:
-%% ipython -p spock
-
-If you want spock extension to be automaticaly active when you start ipython,
-edit your %s and add the line:
-import ipy_profile_spock
-
-Next time, just start ipython on the command line:
-%% ipython
-
-and your spock extension should be loaded automaticaly. Note that if you are
-also loading other extensions that, for example, overwrite the prompt, the
-prompt that will appear is the one from the last extension to be imported.
+%% ipython --profile=spock
 
 For more information goto:
 http://www.tango-controls.org/static/PyTango/latest/doc/html/
 
 Have fun with spock!
 The PyTango team
-    """ % (ipy_user_config,))
-
+""")
+    
 def main():
     d = None
     if len(sys.argv) > 1:
diff --git a/PyTango/ipython/ipython_00_11/ipython_00_11.py b/PyTango/ipython/ipython_00_11/ipython_00_11.py
index f1fdc24..5aa0c73 100644
--- a/PyTango/ipython/ipython_00_11/ipython_00_11.py
+++ b/PyTango/ipython/ipython_00_11/ipython_00_11.py
@@ -25,24 +25,29 @@
 
 """An IPython profile designed to provide a user friendly interface to Tango"""
 
+__all__ = ["load_config", "load_ipython_extension", "unload_ipython_extension"]
+
 import sys
 import os
 import re
 import StringIO
 import textwrap
-import IPython.ColorANSI
-import IPython.Prompts
-import IPython.PyColorize
-import IPython.excolors
-import IPython.ipstruct
-import IPython.genutils
 
 from IPython.core import ipapi
 from IPython.core.error import UsageError
+from IPython.utils.ipstruct import Struct
+from IPython.core.page import page
 
 import PyTango
 import PyTango.utils
 
+_TG_EXCEPTIONS = PyTango.DevFailed, PyTango.CommunicationFailed, \
+    PyTango.NamedDevFailed, PyTango.NamedDevFailedList, \
+    PyTango.WrongNameSyntax, PyTango.NonDbDevice, PyTango.WrongData, \
+    PyTango.NonSupportedFeature, PyTango.AsynCall, \
+    PyTango.AsynReplyNotArrived, PyTango.EventSystemFailed, \
+    PyTango.DeviceUnlocked, PyTango.NotAllowed
+
 _DB_SYMB = "db"
 _DFT_TANGO_HOST = None
 _SPOCK_STORE = "__spock_store"
@@ -82,7 +87,7 @@ class DeviceClassCompleter(object):
 def __DeviceProxy_completer(ip, evt):
     db = __get_db()
     if db is None: return
-    ret = db._db_cache.deviIPyhces.keys()
+    ret = db._db_cache.devices.keys()
     ret.extend(db._db_cache.aliases.keys())
     return ret
 
@@ -253,7 +258,7 @@ def magic_lsdev(self, parameter_s=''):
         if reg_exp and not reg_exp.match(d): continue
         print >>s, l % (d, v[0], v[1], v[2])
     s.seek(0)
-    IPython.genutils.page(s.read())
+    page(s.read())
 
 def magic_lsdevclass(self, parameter_s=''):
     """Lists all known tango device classes.
@@ -278,7 +283,7 @@ def magic_lsdevclass(self, parameter_s=''):
     s = StringIO.StringIO()
     data = [ "%-030s" % klass for klass in data.keys() if not reg_exp or reg_exp.match(klass) ]
     s = textwrap.fill(" ".join(data), 80)
-    IPython.genutils.page(s)
+    page(s)
 
 def magic_lsserv(self, parameter_s=''):
     """Lists all known tango servers.
@@ -303,7 +308,7 @@ def magic_lsserv(self, parameter_s=''):
     s = StringIO.StringIO()
     data = [ "%-030s" % server for server in data.keys() if not reg_exp or reg_exp.match(server) ]
     s = textwrap.fill(" ".join(data), 80)
-    IPython.genutils.page(s)
+    page(s)
 
 def magic_tango_error(self, parameter_s=''):
     """Displays detailed information about the last tango error"""
@@ -485,15 +490,15 @@ def get_alias_list():
 # Private helper methods
 #-------------------------------------------------------------------------------
 
-def __tango_exc_handler(ip, etype, value, tb):
+def __tango_exc_handler(ip, etype, value, tb, tb_offset=None):
     global _SPOCK_ERR
-    ip.user_ns[_SPOCK_ERR] = etype, value, tb
-    if etype == PyTango.DevFailed:
+    ip.user_ns[_SPOCK_ERR] = etype, value, tb, tb_offset
+    if issubclass(etype, _TG_EXCEPTIONS):
         if len(value.args):
             v = value[0]
             print v.reason,":",v.desc
         else:
-            print "Empty DevFailed"
+            print "Empty Tango " + str(etype)
         print "For more detailed information type: tango_error"
         
 def __safe_tango_exec(f, *args, **kwargs):
@@ -568,7 +573,7 @@ def __get_db(host_port=None):
                 ip.user_ns["DB_NAME"] = "OFFLINE"
                 
         # register the 'db' in the user namespace
-        ip.to_user_ns({ _DB_SYMB : db })
+        ip.user_ns.update({ _DB_SYMB : db })
         
     return db
 
@@ -589,12 +594,12 @@ def __completer_wrapper(f):
         except Exception, e:
             print
             print "An unexpected exception ocorred during Spock command completer."
-            print "Please send a bug report to the PyTango team with the following informantion:"
-            print ipapi.get().options.banner
+            print "Please send a bug report to the PyTango team with the following information:"
             print 80*"-"
             print "Completer:",__get_obj_name(f)
             print 80*"-"
-            print str(e)
+            import traceback
+            traceback.print_exc()
             print 80*"-"
             raise e
     return wrapper
@@ -604,15 +609,10 @@ def __get_python_version():
 
 def __get_ipython_version():
     """Returns the current IPython version"""
-    v = None
+    import IPython
+    v = "<Unknown>"
     try:
-        try:
-            v = IPython.Release.version
-        except Exception:
-            try:
-                v = IPython.release.version
-            except Exception:
-                pass
+        v = IPython.release.version
     except Exception:
         pass
     return v
@@ -625,7 +625,7 @@ def __get_ipapi():
     return ipapi.get()
 
 def __expose_magic(ip, name, fn, completer_func=None):
-    ip.expose_magic(name, fn)
+    ip.define_magic(name, fn)
     
     if completer_func is None:
         return
@@ -634,15 +634,16 @@ def __expose_magic(ip, name, fn, completer_func=None):
     ip.set_hook('complete_command', completer_func, re_key = ".*" + name)
 
 def __unexpose_magic(ip, name):
-    mg = 'magic_%s' % name
-    delattr(ip.IP, mg)
+    delattr(ip, 'magic_' + name)
 
 def __build_color_scheme(ip, name):
-    
+
+    import IPython.Prompts
+    import IPython.PyColorize
+    import IPython.excolors
+    from IPython.utils.coloransi import TermColors, InputTermColors
+
     # make some schemes as instances so we can copy them for modification easily:
-    ColorANSI = IPython.ColorANSI
-    InputColors = ColorANSI.InputTermColors
-    TermColors = ColorANSI.TermColors
     PromptColors = IPython.Prompts.PromptColors
     ANSICodeColors = IPython.PyColorize.ANSICodeColors
     ExceptionColors = IPython.excolors.ExceptionColors
@@ -658,9 +659,9 @@ def __build_color_scheme(ip, name):
     inspectTangoColors = InspectColors['Linux'].copy(name)
     
     # initialize prompt with default tango colors
-    promptTangoColors.colors.in_prompt  = InputColors.Purple
-    promptTangoColors.colors.in_number  = InputColors.LightPurple
-    promptTangoColors.colors.in_prompt2 = InputColors.Purple
+    promptTangoColors.colors.in_prompt  = InputTermColors.Purple
+    promptTangoColors.colors.in_number  = InputTermColors.LightPurple
+    promptTangoColors.colors.in_prompt2 = InputTermColors.Purple
     promptTangoColors.colors.out_prompt = TermColors.Blue
     promptTangoColors.colors.out_number = TermColors.LightBlue
 
@@ -684,7 +685,10 @@ def __set_store(ip, key=None, value=None):
     __store(ip, _SPOCK_STORE)
 
 def __get_store(ip, key, nvalue=None):
+    # ipython 0.11 doesn't have 'store' magic command so...
     spock_store = ip.user_ns.get(_SPOCK_STORE)
+    if spock_store is None:
+        ip.user_ns[_SPOCK_STORE] = spock_store = {}
     v = spock_store.get(key)
     if v is None and nvalue is not None:
         spock_store[key] = nvalue
@@ -694,6 +698,9 @@ def __get_store(ip, key, nvalue=None):
 def __store(ip, var):
     # this executes the magic command store which prints a lot of info. So, first
     # we hide the standard output 
+    # ipython 0.11 doesn't have 'store' magic command so...
+    return
+
     stdout = sys.stdout
     try:
         sys.stdout = StringIO.StringIO()
@@ -706,7 +713,6 @@ def __store(ip, var):
 #-------------------------------------------------------------------------------
 
 def init_colors(ip):
-    ColorANSI = IPython.ColorANSI
     InputColors = ColorANSI.InputTermColors
     TermColors = ColorANSI.TermColors
     
@@ -759,7 +765,7 @@ def init_pytango(ip):
     ip.set_hook('complete_command', attr_completer, re_key = ".*AttributeProxy[^\w\.]+")
     ip.set_hook('complete_command', attr_completer, re_key = ".*Attribute[^\w\.]+")
     
-    ip.set_custom_exc((PyTango.DevFailed,), __tango_exc_handler)
+    ip.set_custom_exc(_TG_EXCEPTIONS, __tango_exc_handler)
 
 def init_db(ip, parameter_s=''):
     global _DB_SYMB
@@ -829,7 +835,7 @@ def init_db(ip, parameter_s=''):
             print "Failed to add completer for DeviceClass",klass
     
     # expose classes no user namespace
-    ip.to_user_ns(exposed_klasses)
+    ip.user_ns.update(exposed_klasses)
     
     # Initialize attribute information
     query = "SELECT name, alias FROM attribute_alias order by alias"
@@ -850,13 +856,10 @@ def init_db(ip, parameter_s=''):
     attr_alias_list = PyTango.utils.CaselessList(attr_alias_dict.keys())
     
     # Build cache
-    db_cache = IPython.ipstruct.Struct(devices=dev_dict, aliases=alias_dict,
-                                       servers=serv_dict, klasses=klass_dict,
-                                       junk=exposed_klasses,
-                                       attr_aliases=attr_alias_dict,
-                                       device_list=device_list,
-                                       alias_list=alias_list,
-                                       attr_alias_list=attr_alias_list)
+    db_cache = Struct(devices=dev_dict, aliases=alias_dict,
+        servers=serv_dict, klasses=klass_dict, junk=exposed_klasses,
+        attr_aliases=attr_alias_dict, device_list=device_list,
+        alias_list=alias_list, attr_alias_list=attr_alias_list)
     
     db._db_cache = db_cache
 
@@ -879,12 +882,11 @@ def init_store(ip):
     if spock_store is None:
         print "Initializing spock store (should only happen once)"
         spock_store = {}
-        ip.to_user_ns( { _SPOCK_STORE : spock_store} )
+        ip.user_ns.update( { _SPOCK_STORE : spock_store} )
         __store(ip, _SPOCK_STORE)
         
 def init_console(ip):
-    
-    TermColors = IPython.ColorANSI.TermColors
+    from IPython.utils.coloransi import TermColors
     
     d = { "version" : PyTango.Release.version,
           "pyver" : __get_python_version(),
@@ -892,16 +894,14 @@ def init_console(ip):
           "pytangover" : __get_pytango_version() }
     d.update(TermColors.__dict__)
 
-    o = ip.options
-
-    so = IPython.ipstruct.Struct(
-        spock_banner = """%(Blue)shint: Try typing: mydev = Device("%(LightBlue)s<tab>%(Normal)s\n""")
+    so = Struct(
+        spock_banner="""%(Blue)shint: Try typing: mydev = Device("%(LightBlue)s<tab>%(Normal)s\n""")
 
     so = ip.user_ns.get("spock_options", so)
     
-    o.colors = "Tango"
-    o.prompt_in1 = "Spock <$DB_NAME> [\\#]: "
-    o.prompt_out = "Result [\\#]: "
+    ip.colors = "Linux"
+    ip.prompt_in1 = "Spock <$DB_NAME> [\\#]: "
+    ip.prompt_out = "Result [\\#]: "
     banner = """
 %(Purple)sSpock %(version)s%(Normal)s -- An interactive %(Purple)sTango%(Normal)s client.
 
@@ -911,9 +911,9 @@ help      -> Spock's help system.
 object?   -> Details about 'object'. ?object also works, ?? prints more.
 
 """ + so.spock_banner
-    o.banner = banner % d
-    if hasattr(o.banner, "format"):
-        o.banner = o.banner.format(**d)
+    ip.banner = banner % d
+    if hasattr(ip.banner, "format"):
+        ip.banner = ip.banner.format(**d)
     
 def init_magic(ip):
     __expose_magic(ip, "refreshdb", magic_refreshdb)
@@ -926,7 +926,7 @@ def init_magic(ip):
     __expose_magic(ip, "mon", magic_mon, __monitor_completer)
     #__expose_magic(ip, "umon", magic_umon, __monitor_completer)
     
-    ip.to_user_ns({"get_device_map"   : get_device_map,
+    ip.user_ns.update({"get_device_map"   : get_device_map,
                    "get_server_map"  : get_server_map,
                    "get_class_map"   : get_class_map,
                    "get_alias_map"   : get_alias_map,
@@ -971,7 +971,90 @@ def init_ipython(ip=None, store=True, pytango=True, colors=True, console=True,
     if store:   init_store(ip)
     if pytango: init_pytango(ip)
     init_db(ip)
-    if console: init_console(ip)
+    #if console: init_console(ip)
     if magic:   init_magic(ip)
     
     _spock_init = True
+
+def load_config(config):
+    
+    import IPython.utils.coloransi
+    d = { "version" : PyTango.Release.version,
+          "pyver" : __get_python_version(),
+          "ipyver" : __get_ipython_version(),
+          "pytangover" : __get_pytango_version() }
+    d.update(IPython.utils.coloransi.TermColors.__dict__)
+
+    so = Struct(
+        spock_banner="""%(Blue)shint: Try typing: mydev = Device("%(LightBlue)s<tab>%(Normal)s""")
+
+    so = config.get("spock_options", so)
+
+    # ------------------------------------
+    # Application
+    # ------------------------------------
+    app = config.Application
+    config.log_level = 30
+
+    # ------------------------------------
+    # InteractiveShell
+    # ------------------------------------
+    i_shell = config.InteractiveShell
+    i_shell.colors = "Linux"
+    i_shell.prompt_in1 = "Spock <$DB_NAME> [\\#]: "
+    i_shell.prompt_out = "Result [\\#]: "
+    
+    # ------------------------------------
+    # InteractiveShellApp
+    # ------------------------------------
+    i_shell_app = config.InteractiveShellApp
+    extensions = getattr(i_shell_app, 'extensions', [])
+    extensions.append('PyTango.ipython')
+    i_shell_app.extensions = extensions
+    
+    # ------------------------------------
+    # TerminalIPythonApp: options for the IPython terminal (and not Qt Console)
+    # ------------------------------------
+    term_app = config.TerminalIPythonApp
+    term_app.display_banner = True
+    #term_app.nosep = False
+    #term_app.classic = True
+    
+    # ------------------------------------
+    # IPKernelApp: options for the  Qt Console
+    # ------------------------------------
+    kernel_app = config.IPKernelApp
+    
+    # ------------------------------------
+    # TerminalInteractiveShell
+    # ------------------------------------
+    term_i_shell = config.TerminalInteractiveShell
+    banner = """\
+%(Purple)sSpock %(version)s%(Normal)s -- An interactive %(Purple)sTango%(Normal)s client.
+
+Running on top of Python %(pyver)s, IPython %(ipyver)s and PyTango %(pytangover)s
+
+help      -> Spock's help system.
+object?   -> Details about 'object'. ?object also works, ?? prints more.
+"""
+    
+    banner = banner % d
+    banner = banner.format(**d)
+    spock_banner = so.spock_banner % d
+    spock_banner = spock_banner.format(**d)
+    term_i_shell.banner1 = banner
+    term_i_shell.banner2 = spock_banner
+        
+    
+
+def load_ipython_extension(ipython):
+    # The ``ipython`` argument is the currently active
+    # :class:`InteractiveShell` instance that can be used in any way.
+    # This allows you do to things like register new magics, plugins or
+    # aliases.
+    init_ipython(ip=ipython, store=False, colors=False)
+
+def unload_ipython_extension(ipython):
+    # If you want your extension to be unloadable, put that logic here.
+    #print "Unloading PyTango IPython extension"
+    pass
\ No newline at end of file

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/pytango.git



More information about the debian-science-commits mailing list