コード例 #1
0
ファイル: start_ipython_kernel.py プロジェクト: merbst/spyder
def sympy_config():
    """Sympy configuration"""
    from spyderlib.utils.programs import is_module_installed
    lines_new = """
from sympy.interactive import init_session
init_session()
"""
    lines_old = """
from __future__ import division
from sympy import *
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
"""
    if is_module_installed('sympy', '>=0.7.3'):
        extension = None
        return lines_new, extension
    elif is_module_installed('sympy', '=0.7.2'):
        extension = 'sympy.interactive.ipythonprinting'
        return lines_old, extension
    elif is_module_installed('sympy', '>=0.7.0;<0.7.2'):
        extension = 'sympyprinting'
        return lines_old, extension
    else:
        return None, None
コード例 #2
0
def is_qtconsole_installed():
    if programs.is_module_installed('IPython.qt'):
        return True
    elif programs.is_module_installed('IPython.frontend.qt'):
        return True
    else:
        return False
コード例 #3
0
def is_qtconsole_installed():
    pyzmq_installed = programs.is_module_installed("zmq")
    pygments_installed = programs.is_module_installed("pygments")
    if programs.is_module_installed("IPython.qt") and pyzmq_installed and pygments_installed:
        return True
    else:
        return False
コード例 #4
0
def sympy_config():
    """Sympy configuration"""
    from spyderlib.utils.programs import is_module_installed    
    lines_new = """
from sympy.interactive import init_session
init_session()
"""    
    lines_old = """
from __future__ import division
from sympy import *
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
"""
    if is_module_installed('sympy', '>=0.7.3'):
        extension = None
        return lines_new, extension
    elif is_module_installed('sympy', '=0.7.2'):
        extension = 'sympy.interactive.ipythonprinting'
        return lines_old, extension
    elif is_module_installed('sympy', '>=0.7.0;<0.7.2'):
        extension = 'sympyprinting'
        return lines_old, extension
    else:
        return None, None
コード例 #5
0
def is_qtconsole_installed():
    if programs.is_module_installed('IPython.qt'):
        return True
    elif programs.is_module_installed('IPython.frontend.qt'):
        return True
    else:
        return False
コード例 #6
0
ファイル: ipython.py プロジェクト: jromang/spyderlib
    def show_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner
        
        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            backend_o = CONF.get('ipython_console', 'pylab/backend', 0)
            backends = {0: 'module://IPython.zmq.pylab.backend_inline',
                        1: 'Qt4Agg', 2: 'Qt4Agg', 3: 'MacOSX', 4: 'GTKAgg',
                        5: 'WXAgg', 6: 'TKAgg'}
            pylab_013_message = """
Welcome to pylab, a matplotlib-based Python environment [backend: %s].
For more information, type 'help(pylab)'.\n""" % backends[backend_o]
            pylab_1_message = """
Populating the interactive namespace from numpy and matplotlib"""
            if programs.is_module_installed('IPython', '>=1.0'):
                banner = banner + pylab_1_message
            else:
                banner = banner + pylab_013_message
        
        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
コード例 #7
0
ファイル: ipythonconfig.py プロジェクト: pxwish/spyder
def is_qtconsole_installed():
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    pygments_installed = programs.is_module_installed('pygments')
    if programs.is_module_installed('IPython.qt') and pyzmq_installed \
      and pygments_installed:    
        return True
    else:
        return False
コード例 #8
0
def is_qtconsole_installed():
    pyzmq_installed = programs.is_module_installed('zmq')
    pygments_installed = programs.is_module_installed('pygments')
    if programs.is_module_installed('IPython.qt') and pyzmq_installed \
      and pygments_installed:
        return True
    else:
        return False
コード例 #9
0
def is_qtconsole_installed():
    ipython_installed = programs.is_module_installed('IPython.qt',
                                                     version=IPYTHON_REQVER)
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    pygments_installed = programs.is_module_installed('pygments')

    if ipython_installed and pyzmq_installed and pygments_installed:    
        return True
    else:
        return False
コード例 #10
0
ファイル: ipython.py プロジェクト: s-tazawa/crispy
def is_qtconsole_installed():
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    pygments_installed = programs.is_module_installed('pygments')
    qtconsole_installed = programs.is_module_installed(
        'qtconsole', version=QTCONSOLE_REQVER)

    if pyzmq_installed and pygments_installed and qtconsole_installed:
        return True
    else:
        return False
コード例 #11
0
ファイル: ipython.py プロジェクト: AminJamalzadeh/spyder
def is_qtconsole_installed():
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    pygments_installed = programs.is_module_installed('pygments')
    qtconsole_installed = programs.is_module_installed('qtconsole',
                                                       version=QTCONSOLE_REQVER)

    if pyzmq_installed and pygments_installed and qtconsole_installed:
        return True
    else:
        return False
コード例 #12
0
def is_qtconsole_installed():
    # Only IPython 3+ is compatible with PyQt5, so this will avoid a
    # crash for us
    # TODO: Remove this once IPython 3 is released
    if programs.is_module_installed('IPython.qt', '<3.0') and PYQT5:
        return False

    # Check if pyzmq is installed too, else, what's the point?
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    pygments_installed = programs.is_module_installed('pygments')
    if programs.is_module_installed('IPython.qt') and pyzmq_installed \
      and pygments_installed:
        return True
    else:
        return False
コード例 #13
0
ファイル: status.py プロジェクト: s-tazawa/crispy
 def import_test(self):
     """Raise ImportError if feature is not supported"""
     from spyderlib.utils import programs
     if not programs.is_module_installed('psutil', '>=0.2.0'):
         # The `interval` argument in `psutil.cpu_percent` function
         # was introduced in v0.2.0
         raise ImportError
コード例 #14
0
ファイル: ipython.py プロジェクト: MarvinLiu0810/spyder
    def long_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner
        
        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            pylab_message = ("\nPopulating the interactive namespace from "
                             "numpy and matplotlib")
            banner = banner + pylab_message
        
        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
コード例 #15
0
    def long_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner

        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            pylab_message = ("\nPopulating the interactive namespace from "
                             "numpy and matplotlib")
            banner = banner + pylab_message

        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
コード例 #16
0
ファイル: ipython.py プロジェクト: MarvinLiu0810/spyder
def is_qtconsole_installed():
    ipyqt_installed = programs.is_module_installed('IPython.qt',
                                                   version=IPYTHON_REQVER)
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    pygments_installed = programs.is_module_installed('pygments')

    if ipyqt_installed and pyzmq_installed and pygments_installed:
        if ipy4_installed:
            if programs.is_module_installed('qtconsole'):
                return True
            else:
                return False
        else:
            return True
    else:
        return False
コード例 #17
0
ファイル: jedi_plugin.py プロジェクト: AminJamalzadeh/spyder
 def load_plugin(self):
     """Load the Jedi introspection plugin"""
     if not programs.is_module_installed('jedi', JEDI_REQVER):
         raise ImportError('Requires Jedi %s' % JEDI_REQVER)
     jedi.settings.case_insensitive_completion = False
     for lib in ['numpy', 'matplotlib']:
         jedi.preload_module(lib)
コード例 #18
0
ファイル: status.py プロジェクト: ImadBouirmane/spyder
 def import_test(self):
     """Raise ImportError if feature is not supported"""
     from spyderlib.utils import programs
     if not programs.is_module_installed('psutil', '>=0.2.0'):
         # The `interval` argument in `psutil.cpu_percent` function
         # was introduced in v0.2.0
         raise ImportError
コード例 #19
0
 def _shape_text(self,
                 text,
                 colsep=u("\t"),
                 rowsep=u("\n"),
                 transpose=False,
                 skiprows=0,
                 comments='#'):
     """Decode the shape of the given text"""
     assert colsep != rowsep
     out = []
     text_rows = text.split(rowsep)[skiprows:]
     for row in text_rows:
         stripped = to_text_string(row).strip()
         if len(stripped) == 0 or stripped.startswith(comments):
             continue
         line = to_text_string(row).split(colsep)
         line = [try_to_parse(to_text_string(x)) for x in line]
         out.append(line)
     # Replace missing elements with np.nan's or None's
     if programs.is_module_installed('numpy'):
         from numpy import nan
         out = list(zip_longest(*out, fillvalue=nan))
     else:
         out = list(zip_longest(*out, fillvalue=None))
     # Tranpose the last result to get the expected one
     out = [[r[col] for r in out] for col in range(len(out[0]))]
     if transpose:
         return [[r[col] for r in out] for col in range(len(out[0]))]
     return out
コード例 #20
0
ファイル: externalconsole.py プロジェクト: cheesinglee/spyder
 def open_interpreter_at_startup(self):
     """Open an interpreter at startup, IPython if module is available"""
     if CONF.get(self.ID, 'open_ipython_at_startup') \
        and programs.is_module_installed("IPython"):
         self.open_ipython()
     if CONF.get(self.ID, 'open_python_at_startup'):
         self.open_interpreter()
コード例 #21
0
ファイル: jedi_plugin.py プロジェクト: s-tazawa/crispy
 def load_plugin(self):
     """Load the Jedi introspection plugin"""
     if not programs.is_module_installed('jedi', JEDI_REQVER):
         raise ImportError('Requires Jedi %s' % JEDI_REQVER)
     jedi.settings.case_insensitive_completion = False
     for lib in ['numpy', 'matplotlib']:
         jedi.preload_module(lib)
コード例 #22
0
ファイル: ipythonconfig.py プロジェクト: evekeen/spectracer
def is_qtconsole_installed():
    # Only IPython 3+ is compatible with PyQt5, so this will avoid a
    # crash for us
    # TODO: Remove this once IPython 3 is released
    if programs.is_module_installed('IPython.qt', '<3.0') and PYQT5:
        print "disabled iPython since python < 3.0 and pyqt5"
        return False

    # Check if pyzmq is installed too, else, what's the point?
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    if programs.is_module_installed('IPython.qt') and pyzmq_installed:
        return True
    else:
        if not programs.is_module_installed('IPython.qt'):
            print "disabled iPython no module IPython.qt found"
        print "disabled iPython no module pyzmq found"
        return False
コード例 #23
0
ファイル: jedi_plugin.py プロジェクト: jessebrizzi/spyderDark
 def load_plugin(self):
     """Load the Jedi introspection plugin"""
     if not programs.is_module_installed('jedi', JEDI_REQVER):
         raise ImportError('Requires Jedi %s' % JEDI_REQVER)
     jedi.settings.case_insensitive_completion = False
     self.busy = True
     self._warmup_thread = threading.Thread(target=self.preload)
     self._warmup_thread.start()
コード例 #24
0
ファイル: jedi_plugin.py プロジェクト: ImadBouirmane/spyder
 def load_plugin(self):
     """Load the Jedi introspection plugin"""
     if not programs.is_module_installed('jedi', JEDI_REQVER):
         raise ImportError('Requires Jedi %s' % JEDI_REQVER)
     jedi.settings.case_insensitive_completion = False
     self.busy = True
     self._warmup_thread = threading.Thread(target=self.preload)
     self._warmup_thread.start()
コード例 #25
0
ファイル: rope_plugin.py プロジェクト: AungWinnHtut/spyder
 def load_plugin(self):
     """Load the Rope introspection plugin"""
     if not programs.is_module_installed('rope', ROPE_REQVER):
         raise ImportError('Requires Rope %s' % ROPE_REQVER)
     self.project = None
     self.create_rope_project(root_path=get_conf_path())
     submods = get_preferred_submodules()
     if self.project is not None:
         self.project.prefs.set('extension_modules', submods)
コード例 #26
0
    def setup_page(self):
        ar_group = QGroupBox(_("Autorefresh"))
        ar_box = self.create_checkbox(_("Enable autorefresh"),
                                      'autorefresh')
        ar_spin = self.create_spinbox(_("Refresh interval: "),
                                      _(" ms"), 'autorefresh/timeout',
                                      min_=100, max_=1000000, step=100)
        
        filter_group = QGroupBox(_("Filter"))
        filter_data = [
            ('exclude_private', _("Exclude private references")),
            ('exclude_capitalized', _("Exclude capitalized references")),
            ('exclude_uppercase', _("Exclude all-uppercase references")),
            ('exclude_unsupported', _("Exclude unsupported data types")),
                ]
        filter_boxes = [self.create_checkbox(text, option)
                        for option, text in filter_data]

        display_group = QGroupBox(_("Display"))
        display_data = [
                        ('truncate', _("Truncate values"), ''),
                        ('inplace', _("Always edit in-place"), ''),
                        ('collvalue', _("Show collection contents"), ''),
                        ]
        if programs.is_module_installed('numpy'):
            display_data.append(('minmax', _("Show arrays min/max"), ''))
        display_data.append(
            ('remote_editing', _("Edit data in the remote process"),
             _("Editors are opened in the remote process for NumPy "
                     "arrays, PIL images, lists, tuples and dictionaries.\n"
                     "This avoids transfering large amount of data between "
                     "the remote process and Spyder (through the socket)."))
                            )
        display_boxes = [self.create_checkbox(text, option, tip=tip)
                         for option, text, tip in display_data]
        
        ar_layout = QVBoxLayout()
        ar_layout.addWidget(ar_box)
        ar_layout.addWidget(ar_spin)
        ar_group.setLayout(ar_layout)
        
        filter_layout = QVBoxLayout()
        for box in filter_boxes:
            filter_layout.addWidget(box)
        filter_group.setLayout(filter_layout)

        display_layout = QVBoxLayout()
        for box in display_boxes:
            display_layout.addWidget(box)
        display_group.setLayout(display_layout)

        vlayout = QVBoxLayout()
        vlayout.addWidget(ar_group)
        vlayout.addWidget(filter_group)
        vlayout.addWidget(display_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
コード例 #27
0
ファイル: variableexplorer.py プロジェクト: s-tazawa/crispy
    def setup_page(self):
        ar_group = QGroupBox(_("Autorefresh"))
        ar_box = self.create_checkbox(_("Enable autorefresh"), 'autorefresh')
        ar_spin = self.create_spinbox(_("Refresh interval: "),
                                      _(" ms"),
                                      'autorefresh/timeout',
                                      min_=100,
                                      max_=1000000,
                                      step=100)

        filter_group = QGroupBox(_("Filter"))
        filter_data = [
            ('exclude_private', _("Exclude private references")),
            ('exclude_capitalized', _("Exclude capitalized references")),
            ('exclude_uppercase', _("Exclude all-uppercase references")),
            ('exclude_unsupported', _("Exclude unsupported data types")),
        ]
        filter_boxes = [
            self.create_checkbox(text, option) for option, text in filter_data
        ]

        display_group = QGroupBox(_("Display"))
        display_data = [('truncate', _("Truncate values"), '')]
        if programs.is_module_installed('numpy'):
            display_data.append(('minmax', _("Show arrays min/max"), ''))
        display_data.append(
            ('remote_editing', _("Edit data in the remote process"),
             _("Editors are opened in the remote process for NumPy "
               "arrays, PIL images, lists, tuples and dictionaries.\n"
               "This avoids transfering large amount of data between "
               "the remote process and Spyder (through the socket).")))
        display_boxes = [
            self.create_checkbox(text, option, tip=tip)
            for option, text, tip in display_data
        ]

        ar_layout = QVBoxLayout()
        ar_layout.addWidget(ar_box)
        ar_layout.addWidget(ar_spin)
        ar_group.setLayout(ar_layout)

        filter_layout = QVBoxLayout()
        for box in filter_boxes:
            filter_layout.addWidget(box)
        filter_group.setLayout(filter_layout)

        display_layout = QVBoxLayout()
        for box in display_boxes:
            display_layout.addWidget(box)
        display_group.setLayout(display_layout)

        vlayout = QVBoxLayout()
        vlayout.addWidget(ar_group)
        vlayout.addWidget(filter_group)
        vlayout.addWidget(display_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
コード例 #28
0
ファイル: ipython.py プロジェクト: jromang/spyderlib
 def write_to_stdin(self, line):
     """
     Send raw characters to the IPython kernel through stdin
     but only if the kernel is currently looking for raw input.
     """
     if self._reading:
         if programs.is_module_installed('IPython', '>=1.0'):
             self.kernel_client.stdin_channel.input(line)
         else:
             self.kernel_manager.stdin_channel.input(line)
コード例 #29
0
 def write_to_stdin(self, line):
     """
     Send raw characters to the IPython kernel through stdin
     but only if the kernel is currently looking for raw input.
     """
     if self._reading:
         if programs.is_module_installed('IPython', '>=1.0'):
             self.kernel_client.stdin_channel.input(line)
         else:
             self.kernel_manager.stdin_channel.input(line)
コード例 #30
0
ファイル: ipython.py プロジェクト: jromang/spyderlib
 def closeEvent(self, event):
     """
     Reimplement Qt method to stop sending the custom_restart_kernel_died
     signal
     """
     if programs.is_module_installed('IPython', '>=1.0'):
         kc = self.shellwidget.kernel_client
         if kc is not None:
             kc.hb_channel.pause()
     else:
         self.shellwidget.custom_restart = False
コード例 #31
0
ファイル: qthelpers.py プロジェクト: cheesinglee/spyder
def create_module_bookmark_actions(parent, bookmarks):
    """
    Create bookmark actions depending on module installation:
    bookmarks = ((module_name, url, title), ...)
    """
    actions = []
    for key, url, title, icon in bookmarks:
        if programs.is_module_installed(key):
            act = create_bookmark_action(parent, url, title, get_icon(icon))
            actions.append(act)
    return actions
コード例 #32
0
ファイル: ipythonconsole.py プロジェクト: Poneyo/spyderlib
 def kernel_and_frontend_match(self, connection_file):
     # Determine kernel version
     ci = get_connection_info(connection_file, unpack=True,
                              profile='default')
     if u('control_port') in ci:
         kernel_ver = '>=1.0'
     else:
         kernel_ver = '<1.0'
     # is_module_installed checks if frontend version agrees with the
     # kernel one
     return programs.is_module_installed('IPython', version=kernel_ver)
コード例 #33
0
 def closeEvent(self, event):
     """
     Reimplement Qt method to stop sending the custom_restart_kernel_died
     signal
     """
     if programs.is_module_installed('IPython', '>=1.0'):
         kc = self.shellwidget.kernel_client
         if kc is not None:
             kc.hb_channel.pause()
     else:
         self.shellwidget.custom_restart = False
コード例 #34
0
    def show_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner

        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            backend_o = CONF.get('ipython_console', 'pylab/backend', 0)
            backends = {
                0: 'module://IPython.zmq.pylab.backend_inline',
                1: 'Qt4Agg',
                2: 'Qt4Agg',
                3: 'MacOSX',
                4: 'GTKAgg',
                5: 'WXAgg',
                6: 'TKAgg'
            }
            pylab_013_message = """
Welcome to pylab, a matplotlib-based Python environment [backend: %s].
For more information, type 'help(pylab)'.\n""" % backends[backend_o]
            pylab_1_message = """
Populating the interactive namespace from numpy and matplotlib"""
            if programs.is_module_installed('IPython', '>=1.0'):
                banner = banner + pylab_1_message
            else:
                banner = banner + pylab_013_message

        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
コード例 #35
0
 def create_kernel_manager_and_client(self,
                                      connection_file=None,
                                      hostname=None,
                                      sshkey=None,
                                      password=None):
     """Create kernel manager and client"""
     cf = find_connection_file(connection_file, profile='default')
     kernel_manager = QtKernelManager(connection_file=cf, config=None)
     if programs.is_module_installed('IPython', '>=1.0'):
         kernel_client = kernel_manager.client()
         kernel_client.load_connection_file()
         if hostname is not None:
             try:
                 newports = tunnel_to_kernel(
                     dict(ip=kernel_client.ip,
                          shell_port=kernel_client.shell_port,
                          iopub_port=kernel_client.iopub_port,
                          stdin_port=kernel_client.stdin_port,
                          hb_port=kernel_client.hb_port), hostname, sshkey,
                     password)
                 (kernel_client.shell_port, kernel_client.iopub_port,
                  kernel_client.stdin_port,
                  kernel_client.hb_port) = newports
             except Exception as e:
                 QMessageBox.critical(
                     self, _('Connection error'),
                     _('Could not open ssh tunnel\n') + str(e))
                 return None, None
         kernel_client.start_channels()
         # To rely on kernel's heartbeat to know when a kernel has died
         kernel_client.hb_channel.unpause()
         return kernel_manager, kernel_client
     else:
         kernel_manager.load_connection_file()
         if hostname is not None:
             try:
                 newports = tunnel_to_kernel(
                     dict(ip=kernel_manager.ip,
                          shell_port=kernel_manager.shell_port,
                          iopub_port=kernel_manager.iopub_port,
                          stdin_port=kernel_manager.stdin_port,
                          hb_port=kernel_manager.hb_port), hostname, sshkey,
                     password)
                 (kernel_manager.shell_port, kernel_manager.iopub_port,
                  kernel_manager.stdin_port,
                  kernel_manager.hb_port) = newports
             except Exception as e:
                 QMessageBox.critical(
                     self, _('Connection error'),
                     _('Could not open ssh tunnel\n') + str(e))
                 return None, None
         kernel_manager.start_channels()
         return kernel_manager, None
コード例 #36
0
 def kernel_and_frontend_match(self, connection_file):
     # Determine kernel version
     ci = get_connection_info(connection_file,
                              unpack=True,
                              profile='default')
     if u('control_port') in ci:
         kernel_ver = '>=1.0'
     else:
         kernel_ver = '<1.0'
     # is_module_installed checks if frontend version agrees with the
     # kernel one
     return programs.is_module_installed('IPython', version=kernel_ver)
コード例 #37
0
 def create_kernel_manager_and_client(self, connection_file=None):
     """Create kernel manager and client"""
     cf = find_connection_file(connection_file, profile='default')
     kernel_manager = QtKernelManager(connection_file=cf, config=None)
     if programs.is_module_installed('IPython', '>=1.0'):
         kernel_client = kernel_manager.client()
         kernel_client.load_connection_file()
         kernel_client.start_channels()
         # To rely on kernel's heartbeat to know when a kernel has died
         kernel_client.hb_channel.unpause()
     else:
         kernel_client = None
         kernel_manager.load_connection_file()
         kernel_manager.start_channels()
     return kernel_manager, kernel_client
コード例 #38
0
ファイル: externalconsole.py プロジェクト: cheesinglee/spyder
 def get_default_ipython_options(self):
     """Return default ipython command line arguments"""
     default_options = []
     if programs.is_module_installed('matplotlib'):
         default_options.append("-pylab")
     else:
         default_options.append("-q4thread")
     default_options.append("-colors LightBG")
     default_options.append("-xmode Plain")
     for editor_name in ("scite", "gedit"):
         real_name = programs.get_nt_program_name(editor_name)
         if programs.is_program_installed(real_name):
             default_options.append("-editor "+real_name)
             break
     return " ".join(default_options)
コード例 #39
0
 def load_plugin(self):
     """Load the Rope introspection plugin"""
     if not programs.is_module_installed('rope', ROPE_REQVER):
         raise ImportError('Requires Rope %s' % ROPE_REQVER)
     self.project = None
     self.create_rope_project(root_path=get_conf_path())
     submods = get_preferred_submodules()
     actual = []
     for submod in submods:
         try:
             imp.find_module(submod)
             actual.append(submod)
         except ImportError:
             pass
     if self.project is not None:
         self.project.prefs.set('extension_modules', actual)
コード例 #40
0
ファイル: iofuncs.py プロジェクト: cheesinglee/spyder
 def get_3rd_party_funcs(self):
     other_funcs = []
     from spyderlib.utils import programs
     if programs.is_module_installed("spyderplugins"):
         import spyderplugins
         path = spyderplugins.__path__[0]
         for name in os.listdir(path):
             modname, ext = osp.splitext(name)
             if name.startswith('io_') and ext == '.py':
                 mod = getattr(__import__('spyderplugins.%s' % modname),
                               modname)
                 try:
                     other_funcs.append((mod.FORMAT_EXT, mod.FORMAT_NAME,
                                         mod.FORMAT_LOAD, mod.FORMAT_SAVE))
                 except AttributeError, error:
                     print >>STDERR, "%s: %s" % (mod, str(error))
コード例 #41
0
ファイル: rope_plugin.py プロジェクト: AminJamalzadeh/spyder
 def load_plugin(self):
     """Load the Rope introspection plugin"""
     if not programs.is_module_installed('rope', ROPE_REQVER):
         raise ImportError('Requires Rope %s' % ROPE_REQVER)
     self.project = None
     self.create_rope_project(root_path=get_conf_path())
     submods = get_preferred_submodules()
     actual = []
     for submod in submods:
         try:
             imp.find_module(submod)
             actual.append(submod)
         except ImportError:
             pass
     if self.project is not None:
         self.project.prefs.set('extension_modules', actual)
コード例 #42
0
ファイル: qthelpers.py プロジェクト: jromang/spyderlib
def create_module_bookmark_actions(parent, bookmarks):
    """
    Create bookmark actions depending on module installation:
    bookmarks = ((module_name, url, title), ...)
    """
    actions = []
    for key, url, title in bookmarks:
        # Create actions for scientific distros only if Spyder is installed
        # under them
        create_act = True
        if key == 'xy' or key == 'winpython':
            if not programs.is_module_installed(key):
                create_act = False
        if create_act:
            act = create_bookmark_action(parent, url, title)
            actions.append(act)
    return actions
コード例 #43
0
ファイル: qthelpers.py プロジェクト: evekeen/spectracer
def create_module_bookmark_actions(parent, bookmarks):
    """
    Create bookmark actions depending on module installation:
    bookmarks = ((module_name, url, title), ...)
    """
    actions = []
    for key, url, title in bookmarks:
        # Create actions for scientific distros only if Spyder is installed
        # under them
        create_act = True
        if key == 'xy' or key == 'winpython':
            if not programs.is_module_installed(key):
                create_act = False
        if create_act:
            act = create_bookmark_action(parent, url, title)
            actions.append(act)
    return actions
コード例 #44
0
ファイル: ipythonconsole.py プロジェクト: Poneyo/spyderlib
 def create_kernel_manager_and_client(self, connection_file=None,
                                      hostname=None, sshkey=None,
                                      password=None):
     """Create kernel manager and client"""
     cf = find_connection_file(connection_file, profile='default')
     kernel_manager = QtKernelManager(connection_file=cf, config=None)
     if programs.is_module_installed('IPython', '>=1.0'):
         kernel_client = kernel_manager.client()
         kernel_client.load_connection_file()
         if hostname is not None:
             try:
                 newports = tunnel_to_kernel(dict(ip=kernel_client.ip,
                                       shell_port=kernel_client.shell_port,
                                       iopub_port=kernel_client.iopub_port,
                                       stdin_port=kernel_client.stdin_port,
                                       hb_port=kernel_client.hb_port),
                                       hostname, sshkey, password)
                 (kernel_client.shell_port, kernel_client.iopub_port,
                  kernel_client.stdin_port, kernel_client.hb_port) = newports
             except Exception as e:
                 QMessageBox.critical(self, _('Connection error'), 
                                  _('Could not open ssh tunnel\n') + str(e))
                 return None, None
         kernel_client.start_channels()
         # To rely on kernel's heartbeat to know when a kernel has died
         kernel_client.hb_channel.unpause()
         return kernel_manager, kernel_client
     else:
         kernel_manager.load_connection_file()
         if hostname is not None:
             try:
                 newports = tunnel_to_kernel(dict(ip=kernel_manager.ip,
                                       shell_port=kernel_manager.shell_port,
                                       iopub_port=kernel_manager.iopub_port,
                                       stdin_port=kernel_manager.stdin_port,
                                       hb_port=kernel_manager.hb_port),
                                       hostname, sshkey, password)
                 (kernel_manager.shell_port, kernel_manager.iopub_port,
                  kernel_manager.stdin_port, kernel_manager.hb_port) = newports
             except Exception as e:
                 QMessageBox.critical(self, _('Connection error'), 
                                  _('Could not open ssh tunnel\n') + str(e))
                 return None, None
         kernel_manager.start_channels()
         return kernel_manager, None
コード例 #45
0
ファイル: explorer.py プロジェクト: jromang/retina-old
 def create_folder_manage_actions(self, fnames):
     """Return folder management actions"""
     actions = []
     if os.name == 'nt':
         _title = _("Open command prompt here")
     else:
         _title = _("Open terminal here")
     action = create_action(self, _title, icon="cmdprompt.png",
                            triggered=lambda fnames=fnames:
                            self.open_terminal(fnames))
     actions.append(action)
     _title = _("Open Python interpreter here")
     action = create_action(self, _title, icon="python.png",
                            triggered=lambda fnames=fnames:
                            self.open_interpreter(fnames))
     actions.append(action)
     if programs.is_module_installed('IPython', '0.1'):
         _title = _("Open IPython here")
         action = create_action(self, _title, icon="ipython.png",
                                triggered=lambda fnames=fnames:
                                self.open_ipython(fnames))
         actions.append(action)
     return actions
コード例 #46
0
ファイル: importwizard.py プロジェクト: gyenney/Tools
    def _shape_text(self, text, colsep=u"\t", rowsep=u"\n", transpose=False, skiprows=0, comments="#"):
        """Decode the shape of the given text"""
        assert colsep != rowsep
        out = []
        text_rows = text.split(rowsep)[skiprows:]
        for row in text_rows:
            stripped = to_text_string(row).strip()
            if len(stripped) == 0 or stripped.startswith(comments):
                continue
            line = to_text_string(row).split(colsep)
            line = [try_to_parse(to_text_string(x)) for x in line]
            out.append(line)
        # Replace missing elements with np.nan's or None's
        if programs.is_module_installed("numpy"):
            from numpy import nan

            out = list(zip_longest(*out, fillvalue=nan))
        else:
            out = list(zip_longest(*out, fillvalue=None))
        # Tranpose the last result to get the expected one
        out = [[r[col] for r in out] for col in range(len(out[0]))]
        if transpose:
            return [[r[col] for r in out] for col in range(len(out[0]))]
        return out
コード例 #47
0
    def setup(self,
              check_all=None,
              exclude_private=None,
              exclude_uppercase=None,
              exclude_capitalized=None,
              exclude_unsupported=None,
              excluded_names=None,
              truncate=None,
              minmax=None,
              remote_editing=None,
              autorefresh=None):
        """Setup the namespace browser"""
        assert self.shellwidget is not None

        self.check_all = check_all
        self.exclude_private = exclude_private
        self.exclude_uppercase = exclude_uppercase
        self.exclude_capitalized = exclude_capitalized
        self.exclude_unsupported = exclude_unsupported
        self.excluded_names = excluded_names
        self.truncate = truncate
        self.minmax = minmax
        self.remote_editing = remote_editing
        self.autorefresh = autorefresh

        if self.editor is not None:
            self.editor.setup_menu(truncate, minmax)
            self.exclude_private_action.setChecked(exclude_private)
            self.exclude_uppercase_action.setChecked(exclude_uppercase)
            self.exclude_capitalized_action.setChecked(exclude_capitalized)
            self.exclude_unsupported_action.setChecked(exclude_unsupported)
            # Don't turn autorefresh on for IPython kernels
            # See Issue 1450
            if not self.is_ipykernel:
                self.auto_refresh_button.setChecked(autorefresh)
            self.refresh_table()
            return

        # Dict editor:
        if self.is_internal_shell:
            self.editor = CollectionsEditorTableView(self,
                                                     None,
                                                     truncate=truncate,
                                                     minmax=minmax)
        else:
            self.editor = RemoteCollectionsEditorTableView(
                self,
                None,
                truncate=truncate,
                minmax=minmax,
                remote_editing=remote_editing,
                get_value_func=self.get_value,
                set_value_func=self.set_value,
                new_value_func=self.set_value,
                remove_values_func=self.remove_values,
                copy_value_func=self.copy_value,
                is_list_func=self.is_list,
                get_len_func=self.get_len,
                is_array_func=self.is_array,
                is_image_func=self.is_image,
                is_dict_func=self.is_dict,
                is_data_frame_func=self.is_data_frame,
                is_series_func=self.is_series,
                get_array_shape_func=self.get_array_shape,
                get_array_ndim_func=self.get_array_ndim,
                oedit_func=self.oedit,
                plot_func=self.plot,
                imshow_func=self.imshow,
                show_image_func=self.show_image)
        self.editor.sig_option_changed.connect(self.sig_option_changed.emit)
        self.editor.sig_files_dropped.connect(self.import_data)

        # Setup layout
        layout = QVBoxLayout()
        blayout = QHBoxLayout()
        toolbar = self.setup_toolbar(exclude_private, exclude_uppercase,
                                     exclude_capitalized, exclude_unsupported,
                                     autorefresh)
        for widget in toolbar:
            blayout.addWidget(widget)

        # Options menu
        options_button = create_toolbutton(self,
                                           text=_('Options'),
                                           icon=ima.icon('tooloptions'))
        options_button.setPopupMode(QToolButton.InstantPopup)
        menu = QMenu(self)
        editor = self.editor
        actions = [
            self.exclude_private_action, self.exclude_uppercase_action,
            self.exclude_capitalized_action, self.exclude_unsupported_action,
            None, editor.truncate_action
        ]
        if is_module_installed('numpy'):
            actions.append(editor.minmax_action)
        add_actions(menu, actions)
        options_button.setMenu(menu)

        blayout.addStretch()
        blayout.addWidget(options_button)
        layout.addLayout(blayout)
        layout.addWidget(self.editor)
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)

        self.sig_option_changed.connect(self.option_changed)
コード例 #48
0
    def setup_page(self):
        newcb = self.create_checkbox
        mpl_present = programs.is_module_installed("matplotlib")

        # --- Display ---
        font_group = self.create_fontgroup(
            option=None, text=None, fontfilters=QFontComboBox.MonospacedFonts)

        # Interface Group
        interface_group = QGroupBox(_("Interface"))
        banner_box = newcb(
            _("Display initial banner"),
            'show_banner',
            tip=_("This option lets you hide the message shown at\n"
                  "the top of the console when it's opened."))
        gui_comp_box = newcb(_("Use a completion widget"),
                             'use_gui_completion',
                             tip=_("Use a widget instead of plain text "
                                   "output for tab completion"))
        pager_box = newcb(_("Use a pager to display additional text inside "
                            "the console"),
                          'use_pager',
                          tip=_("Useful if you don't want to fill the "
                                "console with long help or completion texts.\n"
                                "Note: Use the Q key to get out of the "
                                "pager."))
        calltips_box = newcb(_("Display balloon tips"), 'show_calltips')
        ask_box = newcb(_("Ask for confirmation before closing"),
                        'ask_before_closing')

        interface_layout = QVBoxLayout()
        interface_layout.addWidget(banner_box)
        interface_layout.addWidget(gui_comp_box)
        interface_layout.addWidget(pager_box)
        interface_layout.addWidget(calltips_box)
        interface_layout.addWidget(ask_box)
        interface_group.setLayout(interface_layout)

        # Background Color Group
        bg_group = QGroupBox(_("Background color"))
        light_radio = self.create_radiobutton(_("Light background"),
                                              'light_color')
        dark_radio = self.create_radiobutton(_("Dark background"),
                                             'dark_color')
        bg_layout = QVBoxLayout()
        bg_layout.addWidget(light_radio)
        bg_layout.addWidget(dark_radio)
        bg_group.setLayout(bg_layout)

        # Source Code Group
        source_code_group = QGroupBox(_("Source code"))
        buffer_spin = self.create_spinbox(
            _("Buffer:  "),
            _(" lines"),
            'buffer_size',
            min_=-1,
            max_=1000000,
            step=100,
            tip=_("Set the maximum number of lines of text shown in the\n"
                  "console before truncation. Specifying -1 disables it\n"
                  "(not recommended!)"))
        source_code_layout = QVBoxLayout()
        source_code_layout.addWidget(buffer_spin)
        source_code_group.setLayout(source_code_layout)

        # --- Graphics ---
        # Pylab Group
        pylab_group = QGroupBox(_("Support for graphics (Matplotlib)"))
        pylab_box = newcb(_("Activate support"), 'pylab')
        autoload_pylab_box = newcb(
            _("Automatically load Pylab and NumPy "
              "modules"),
            'pylab/autoload',
            tip=_("This lets you load graphics support "
                  "without importing \nthe commands to do "
                  "plots. Useful to work with other\n"
                  "plotting libraries different to "
                  "Matplotlib or to develop \nGUIs with "
                  "Spyder."))
        autoload_pylab_box.setEnabled(self.get_option('pylab') and mpl_present)
        self.connect(pylab_box, SIGNAL("toggled(bool)"),
                     autoload_pylab_box.setEnabled)

        pylab_layout = QVBoxLayout()
        pylab_layout.addWidget(pylab_box)
        pylab_layout.addWidget(autoload_pylab_box)
        pylab_group.setLayout(pylab_layout)

        if not mpl_present:
            self.set_option('pylab', False)
            self.set_option('pylab/autoload', False)
            pylab_group.setEnabled(False)
            pylab_tip = _("This feature requires the Matplotlib library.\n"
                          "It seems you don't have it installed.")
            pylab_box.setToolTip(pylab_tip)

        # Pylab backend Group
        inline = _("Inline")
        automatic = _("Automatic")
        backend_group = QGroupBox(_("Graphics backend"))
        bend_label = QLabel(
            _("Decide how graphics are going to be displayed "
              "in the console. If unsure, please select "
              "<b>%s</b> to put graphics inside the "
              "console or <b>%s</b> to interact with "
              "them (through zooming and panning) in a "
              "separate window.") % (inline, automatic))
        bend_label.setWordWrap(True)

        backends = [(inline, 0), (automatic, 1), ("Qt", 2)]
        # TODO: Add gtk3 when 0.13 is released
        if sys.platform == 'darwin':
            backends.append(("Mac OSX", 3))
        if programs.is_module_installed('pygtk'):
            backends.append(("Gtk", 4))
        if programs.is_module_installed('wxPython'):
            backends.append(("Wx", 5))
        if programs.is_module_installed('_tkinter'):
            backends.append(("Tkinter", 6))
        backends = tuple(backends)

        backend_box = self.create_combobox(
            _("Backend:") + "   ",
            backends,
            'pylab/backend',
            default=0,
            tip=_("This option will be applied the "
                  "next time a console is opened."))

        backend_layout = QVBoxLayout()
        backend_layout.addWidget(bend_label)
        backend_layout.addWidget(backend_box)
        backend_group.setLayout(backend_layout)
        backend_group.setEnabled(self.get_option('pylab') and mpl_present)
        self.connect(pylab_box, SIGNAL("toggled(bool)"),
                     backend_group.setEnabled)

        # Inline backend Group
        inline_group = QGroupBox(_("Inline backend"))
        inline_label = QLabel(
            _("Decide how to render the figures created by "
              "this backend"))
        inline_label.setWordWrap(True)
        formats = (("PNG", 0), ("SVG", 1))
        format_box = self.create_combobox(_("Format:") + "   ",
                                          formats,
                                          'pylab/inline/figure_format',
                                          default=0)
        resolution_spin = self.create_spinbox(
            _("Resolution:") + "  ",
            " " + _("dpi"),
            'pylab/inline/resolution',
            min_=56,
            max_=112,
            step=1,
            tip=_("Only used when the format is PNG. Default is "
                  "72"))
        width_spin = self.create_spinbox(_("Width:") + "  ",
                                         " " + _("inches"),
                                         'pylab/inline/width',
                                         min_=2,
                                         max_=20,
                                         step=1,
                                         tip=_("Default is 6"))
        height_spin = self.create_spinbox(_("Height:") + "  ",
                                          " " + _("inches"),
                                          'pylab/inline/height',
                                          min_=1,
                                          max_=20,
                                          step=1,
                                          tip=_("Default is 4"))

        inline_layout = QVBoxLayout()
        inline_layout.addWidget(inline_label)
        inline_layout.addWidget(format_box)
        inline_layout.addWidget(resolution_spin)
        inline_layout.addWidget(width_spin)
        inline_layout.addWidget(height_spin)
        inline_group.setLayout(inline_layout)
        inline_group.setEnabled(self.get_option('pylab') and mpl_present)
        self.connect(pylab_box, SIGNAL("toggled(bool)"),
                     inline_group.setEnabled)

        # --- Startup ---
        # Run lines Group
        run_lines_group = QGroupBox(_("Run code"))
        run_lines_label = QLabel(
            _("You can run several lines of code when "
              "a console is started. Please introduce "
              "each one separated by commas, for "
              "example:<br>"
              "<i>import os, import sys</i>"))
        run_lines_label.setWordWrap(True)
        run_lines_edit = self.create_lineedit(_("Lines:"),
                                              'startup/run_lines',
                                              '',
                                              alignment=Qt.Horizontal)

        run_lines_layout = QVBoxLayout()
        run_lines_layout.addWidget(run_lines_label)
        run_lines_layout.addWidget(run_lines_edit)
        run_lines_group.setLayout(run_lines_layout)

        # Run file Group
        run_file_group = QGroupBox(_("Run a file"))
        run_file_label = QLabel(
            _("You can also run a whole file at startup "
              "instead of just some lines (This is "
              "similar to have a PYTHONSTARTUP file)."))
        run_file_label.setWordWrap(True)
        file_radio = newcb(_("Use the following file:"),
                           'startup/use_run_file', False)
        run_file_browser = self.create_browsefile('', 'startup/run_file', '')
        run_file_browser.setEnabled(False)
        self.connect(file_radio, SIGNAL("toggled(bool)"),
                     run_file_browser.setEnabled)

        run_file_layout = QVBoxLayout()
        run_file_layout.addWidget(run_file_label)
        run_file_layout.addWidget(file_radio)
        run_file_layout.addWidget(run_file_browser)
        run_file_group.setLayout(run_file_layout)

        # ---- Advanced settings ----
        # Greedy completer group
        greedy_group = QGroupBox(_("Greedy completion"))
        greedy_label = QLabel(
            _("Enable <tt>Tab</tt> completion on elements "
              "of lists, results of function calls, etc, "
              "<i>without</i> assigning them to a "
              "variable.<br>"
              "For example, you can get completions on "
              "things like <tt>li[0].&lt;Tab&gt;</tt> or "
              "<tt>ins.meth().&lt;Tab&gt;</tt>"))
        greedy_label.setWordWrap(True)
        greedy_box = newcb(_("Use the greedy completer"),
                           "greedy_completer",
                           tip="<b>Warning</b>: It can be unsafe because the "
                           "code is actually evaluated when you press "
                           "<tt>Tab</tt>.")

        greedy_layout = QVBoxLayout()
        greedy_layout.addWidget(greedy_label)
        greedy_layout.addWidget(greedy_box)
        greedy_group.setLayout(greedy_layout)

        # Autocall group
        autocall_group = QGroupBox(_("Autocall"))
        autocall_label = QLabel(
            _("Autocall makes IPython automatically call "
              "any callable object even if you didn't type "
              "explicit parentheses.<br>"
              "For example, if you type <i>str 43</i> it "
              "becomes <i>str(43)</i> automatically."))
        autocall_label.setWordWrap(True)

        smart = _('Smart')
        full = _('Full')
        autocall_opts = ((_('Off'), 0), (smart, 1), (full, 2))
        autocall_box = self.create_combobox(
            _("Autocall:  "),
            autocall_opts,
            'autocall',
            default=0,
            tip=_("On <b>%s</b> mode, Autocall is not applied if "
                  "there are no arguments after the callable. On "
                  "<b>%s</b> mode, all callable objects are "
                  "automatically called (even if no arguments are "
                  "present).") % (smart, full))

        autocall_layout = QVBoxLayout()
        autocall_layout.addWidget(autocall_label)
        autocall_layout.addWidget(autocall_box)
        autocall_group.setLayout(autocall_layout)

        # Sympy group
        sympy_group = QGroupBox(_("Symbolic Mathematics"))
        sympy_label = QLabel(
            _("Perfom symbolic operations in the console "
              "(e.g. integrals, derivatives, vector calculus, "
              "etc) and get the outputs in a beautifully "
              "printed style."))
        sympy_label.setWordWrap(True)
        sympy_box = newcb(_("Use symbolic math"),
                          "symbolic_math",
                          tip=_(
                              "This option loads the Sympy library to work "
                              "with.<br>Please refer to its documentation to "
                              "learn how to use it."))

        sympy_layout = QVBoxLayout()
        sympy_layout.addWidget(sympy_label)
        sympy_layout.addWidget(sympy_box)
        sympy_group.setLayout(sympy_layout)

        sympy_present = programs.is_module_installed("sympy")
        if not sympy_present:
            self.set_option("symbolic_math", False)
            sympy_box.setEnabled(False)
            sympy_tip = _("This feature requires the Sympy library.\n"
                          "It seems you don't have it installed.")
            sympy_box.setToolTip(sympy_tip)

        # Prompts group
        prompts_group = QGroupBox(_("Prompts"))
        prompts_label = QLabel(
            _("Modify how Input and Output prompts are "
              "shown in the console."))
        prompts_label.setWordWrap(True)
        in_prompt_edit = self.create_lineedit(
            _("Input prompt:"),
            'in_prompt',
            '',
            _('Default is<br>'
              'In [&lt;span class="in-prompt-number"&gt;'
              '%i&lt;/span&gt;]:'),
            alignment=Qt.Horizontal)
        out_prompt_edit = self.create_lineedit(
            _("Output prompt:"),
            'out_prompt',
            '',
            _('Default is<br>'
              'Out[&lt;span class="out-prompt-number"&gt;'
              '%i&lt;/span&gt;]:'),
            alignment=Qt.Horizontal)

        prompts_layout = QVBoxLayout()
        prompts_layout.addWidget(prompts_label)
        prompts_layout.addWidget(in_prompt_edit)
        prompts_layout.addWidget(out_prompt_edit)
        prompts_group.setLayout(prompts_layout)

        # --- Tabs organization ---
        tabs = QTabWidget()
        tabs.addTab(
            self.create_tab(font_group, interface_group, bg_group,
                            source_code_group), _("Display"))
        tabs.addTab(self.create_tab(pylab_group, backend_group, inline_group),
                    _("Graphics"))
        tabs.addTab(self.create_tab(run_lines_group, run_file_group),
                    _("Startup"))
        tabs.addTab(
            self.create_tab(greedy_group, autocall_group, sympy_group,
                            prompts_group), _("Advanced Settings"))

        vlayout = QVBoxLayout()
        vlayout.addWidget(tabs)
        self.setLayout(vlayout)
コード例 #49
0
ファイル: help.py プロジェクト: yuangs/spyder
    def __init__(self, parent):
        if PYQT5:
            SpyderPluginWidget.__init__(self, parent, main=parent)
        else:
            SpyderPluginWidget.__init__(self, parent)

        self.internal_shell = None

        # Initialize plugin
        self.initialize_plugin()

        self.no_doc_string = _("No further documentation available")

        self._last_console_cb = None
        self._last_editor_cb = None

        self.plain_text = PlainText(self)
        self.rich_text = RichText(self)

        color_scheme = self.get_color_scheme()
        self.set_plain_text_font(self.get_plugin_font(), color_scheme)
        self.plain_text.editor.toggle_wrap_mode(self.get_option('wrap'))

        # Add entries to read-only editor context-menu
        self.wrap_action = create_action(self,
                                         _("Wrap lines"),
                                         toggled=self.toggle_wrap_mode)
        self.wrap_action.setChecked(self.get_option('wrap'))
        self.plain_text.editor.readonly_menu.addSeparator()
        add_actions(self.plain_text.editor.readonly_menu, (self.wrap_action, ))

        self.set_rich_text_font(self.get_plugin_font('rich_text'))

        self.shell = None

        self.external_console = None

        # locked = disable link with Console
        self.locked = False
        self._last_texts = [None, None]
        self._last_editor_doc = None

        # Object name
        layout_edit = QHBoxLayout()
        layout_edit.setContentsMargins(0, 0, 0, 0)
        txt = _("Source")
        if sys.platform == 'darwin':
            source_label = QLabel("  " + txt)
        else:
            source_label = QLabel(txt)
        layout_edit.addWidget(source_label)
        self.source_combo = QComboBox(self)
        self.source_combo.addItems([_("Console"), _("Editor")])
        self.source_combo.currentIndexChanged.connect(self.source_changed)
        if (not programs.is_module_installed('rope')
                and not programs.is_module_installed('jedi', '>=0.8.1')):
            self.source_combo.hide()
            source_label.hide()
        layout_edit.addWidget(self.source_combo)
        layout_edit.addSpacing(10)
        layout_edit.addWidget(QLabel(_("Object")))
        self.combo = ObjectComboBox(self)
        layout_edit.addWidget(self.combo)
        self.object_edit = QLineEdit(self)
        self.object_edit.setReadOnly(True)
        layout_edit.addWidget(self.object_edit)
        self.combo.setMaxCount(self.get_option('max_history_entries'))
        self.combo.addItems(self.load_history())
        self.combo.setItemText(0, '')
        self.combo.valid.connect(lambda valid: self.force_refresh())

        # Plain text docstring option
        self.docstring = True
        self.rich_help = self.get_option('rich_mode', True)
        self.plain_text_action = create_action(self,
                                               _("Plain Text"),
                                               toggled=self.toggle_plain_text)

        # Source code option
        self.show_source_action = create_action(
            self, _("Show Source"), toggled=self.toggle_show_source)

        # Rich text option
        self.rich_text_action = create_action(self,
                                              _("Rich Text"),
                                              toggled=self.toggle_rich_text)

        # Add the help actions to an exclusive QActionGroup
        help_actions = QActionGroup(self)
        help_actions.setExclusive(True)
        help_actions.addAction(self.plain_text_action)
        help_actions.addAction(self.rich_text_action)

        # Automatic import option
        self.auto_import_action = create_action(
            self, _("Automatic import"), toggled=self.toggle_auto_import)
        auto_import_state = self.get_option('automatic_import')
        self.auto_import_action.setChecked(auto_import_state)

        # Lock checkbox
        self.locked_button = create_toolbutton(self,
                                               triggered=self.toggle_locked)
        layout_edit.addWidget(self.locked_button)
        self._update_lock_icon()

        # Option menu
        options_button = create_toolbutton(self,
                                           text=_('Options'),
                                           icon=ima.icon('tooloptions'))
        options_button.setPopupMode(QToolButton.InstantPopup)
        menu = QMenu(self)
        add_actions(menu, [
            self.rich_text_action, self.plain_text_action,
            self.show_source_action, None, self.auto_import_action
        ])
        options_button.setMenu(menu)
        layout_edit.addWidget(options_button)

        if self.rich_help:
            self.switch_to_rich_text()
        else:
            self.switch_to_plain_text()
        self.plain_text_action.setChecked(not self.rich_help)
        self.rich_text_action.setChecked(self.rich_help)
        self.source_changed()

        # Main layout
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addLayout(layout_edit)
        layout.addWidget(self.plain_text)
        layout.addWidget(self.rich_text)
        self.setLayout(layout)

        # Add worker thread for handling rich text rendering
        self._sphinx_thread = SphinxThread(
            html_text_no_doc=warning(self.no_doc_string))
        self._sphinx_thread.html_ready.connect(
            self._on_sphinx_thread_html_ready)
        self._sphinx_thread.error_msg.connect(self._on_sphinx_thread_error_msg)

        # Handle internal and external links
        view = self.rich_text.webview
        if not WEBENGINE:
            view.page().setLinkDelegationPolicy(
                QWebEnginePage.DelegateAllLinks)
        view.linkClicked.connect(self.handle_link_clicks)

        self._starting_up = True
コード例 #50
0
def psutil_phymem_usage():
    """
    Return physical memory usage (float)
    Requires the cross-platform psutil (>=v0.3) library
    (http://code.google.com/p/psutil/)
    """
    import psutil
    # This is needed to avoid a deprecation warning error with
    # newer psutil versions
    try:
        percent = psutil.virtual_memory().percent
    except:
        percent = psutil.phymem_usage().percent
    return percent

if programs.is_module_installed('psutil', '>=0.3.0'):
    #  Function `psutil.phymem_usage` was introduced in psutil v0.3.0
    memory_usage = psutil_phymem_usage
elif os.name == 'nt':
    # Backup plan for Windows platforms
    memory_usage = windows_memory_usage
else:
    raise ImportError("Feature requires psutil 0.3+ on non Windows platforms")


if __name__ == '__main__':
    print("*"*80)
    print(memory_usage.__doc__)
    print(memory_usage())
    if os.name == 'nt':
        #  windll can only be imported if os.name = 'nt' or 'ce'
コード例 #51
0
ファイル: rope_plugin.py プロジェクト: jayhetee/spyder
 def load_plugin(self):
     """Load the Rope introspection plugin"""
     if not programs.is_module_installed('rope', ROPE_REQVER):
         raise ImportError('Requires Rope %s' % ROPE_REQVER)
     self.project = None
     self.create_rope_project(root_path=get_conf_path())
コード例 #52
0
def kernel_config():
    """Create a config object with IPython kernel options"""
    import os

    from IPython.core.application import get_ipython_dir
    from spyderlib.config.main import CONF
    from spyderlib.utils.programs import is_module_installed
    from traitlets.config.loader import Config, load_pyconfig_files

    # ---- IPython config ----
    try:
        profile_path = osp.join(get_ipython_dir(), 'profile_default')
        ip_cfg = load_pyconfig_files(['ipython_config.py',
                                      'ipython_qtconsole_config.py'],
                                      profile_path)
    except:
        ip_cfg = Config()
    
    # ---- Spyder config ----
    spy_cfg = Config()
    
    # Until we implement Issue 1052
    spy_cfg.InteractiveShell.xmode = 'Plain'
    
    # Run lines of code at startup
    run_lines_o = CONF.get('ipython_console', 'startup/run_lines')
    if run_lines_o:
        spy_cfg.IPKernelApp.exec_lines = [x.strip() for x in run_lines_o.split(',')]
    else:
        spy_cfg.IPKernelApp.exec_lines = []
    
    # Pylab configuration
    mpl_backend = None
    mpl_installed = is_module_installed('matplotlib')
    pylab_o = CONF.get('ipython_console', 'pylab')
    external_interpreter = \
                   os.environ.get('EXTERNAL_INTERPRETER', '').lower() == "true"

    if mpl_installed and pylab_o:
        # Get matplotlib backend
        if not external_interpreter:
            if os.environ["QT_API"] == 'pyqt5':
                qt_backend = 'qt5'
            else:
                qt_backend = 'qt'

            backend_o = CONF.get('ipython_console', 'pylab/backend', 0)
            backends = {0: 'inline', 1: qt_backend, 2: qt_backend, 3: 'osx',
                        4: 'gtk', 5: 'wx', 6: 'tk'}
            mpl_backend = backends[backend_o]
        else:
            mpl_backend = 'inline'

        # Automatically load Pylab and Numpy, or only set Matplotlib
        # backend
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload')
        if autoload_pylab_o:
            spy_cfg.IPKernelApp.exec_lines.append(
                                              "%pylab {0}".format(mpl_backend))
        else:
            spy_cfg.IPKernelApp.exec_lines.append(
                                         "%matplotlib {0}".format(mpl_backend))

        # Inline backend configuration
        if backends[backend_o] == 'inline':
           # Figure format
           format_o = CONF.get('ipython_console',
                               'pylab/inline/figure_format', 0)
           formats = {0: 'png', 1: 'svg'}
           spy_cfg.InlineBackend.figure_format = formats[format_o]
           
           # Resolution
           spy_cfg.InlineBackend.rc = {'figure.figsize': (6.0, 4.0),
                                   'savefig.dpi': 72,
                                   'font.size': 10,
                                   'figure.subplot.bottom': .125,
                                   'figure.facecolor': 'white',
                                   'figure.edgecolor': 'white'
                                   }
           resolution_o = CONF.get('ipython_console', 
                                   'pylab/inline/resolution')
           spy_cfg.InlineBackend.rc['savefig.dpi'] = resolution_o
           
           # Figure size
           width_o = float(CONF.get('ipython_console', 'pylab/inline/width'))
           height_o = float(CONF.get('ipython_console', 'pylab/inline/height'))
           spy_cfg.InlineBackend.rc['figure.figsize'] = (width_o, height_o)
    
    # Run a file at startup
    use_file_o = CONF.get('ipython_console', 'startup/use_run_file')
    run_file_o = CONF.get('ipython_console', 'startup/run_file')
    if use_file_o and run_file_o:
        spy_cfg.IPKernelApp.file_to_run = run_file_o
    
    # Autocall
    autocall_o = CONF.get('ipython_console', 'autocall')
    spy_cfg.ZMQInteractiveShell.autocall = autocall_o
    
    # To handle the banner by ourselves in IPython 3+
    spy_cfg.ZMQInteractiveShell.banner1 = ''
    
    # Greedy completer
    greedy_o = CONF.get('ipython_console', 'greedy_completer')
    spy_cfg.IPCompleter.greedy = greedy_o
    
    # Sympy loading
    sympy_o = CONF.get('ipython_console', 'symbolic_math')
    if sympy_o:
        lines = sympy_config(mpl_backend)
        spy_cfg.IPKernelApp.exec_lines.append(lines)

    # Merge IPython and Spyder configs. Spyder prefs will have prevalence
    # over IPython ones
    ip_cfg._merge(spy_cfg)
    return ip_cfg
コード例 #53
0
# Constants
IPYTHON_REQVER = '>=3.0'
ZMQ_REQVER = '>=13.0.0'
QTCONSOLE_REQVER = '>=4.0'

# Dependencies
dependencies.add("IPython",
                 _("IPython Console integration"),
                 required_version=IPYTHON_REQVER)
dependencies.add("zmq",
                 _("IPython Console integration"),
                 required_version=ZMQ_REQVER)

# Jupyter 4.0 requirements
ipy4_installed = programs.is_module_installed('IPython', '>=4.0')
if ipy4_installed:
    dependencies.add("qtconsole",
                     _("IPython Console integration"),
                     required_version=QTCONSOLE_REQVER)


# Auxiliary functions
def is_qtconsole_installed():
    ipyqt_installed = programs.is_module_installed('IPython.qt',
                                                   version=IPYTHON_REQVER)
    pyzmq_installed = programs.is_module_installed('zmq', version=ZMQ_REQVER)
    pygments_installed = programs.is_module_installed('pygments')

    if ipyqt_installed and pyzmq_installed and pygments_installed:
        if ipy4_installed:
コード例 #54
0
ファイル: help.py プロジェクト: yuangs/spyder
    def setup_page(self):
        # Connections group
        connections_group = QGroupBox(_("Automatic connections"))
        connections_label = QLabel(
            _("This pane can automatically "
              "show an object's help information after "
              "a left parenthesis is written next to it. "
              "Below you can decide to which plugin "
              "you want to connect it to turn on this "
              "feature."))
        connections_label.setWordWrap(True)
        editor_box = self.create_checkbox(_("Editor"), 'connect/editor')
        rope_installed = programs.is_module_installed('rope')
        jedi_installed = programs.is_module_installed('jedi', '>=0.8.1')
        editor_box.setEnabled(rope_installed or jedi_installed)
        if not rope_installed and not jedi_installed:
            editor_tip = _(
                "This feature requires the Rope or Jedi libraries.\n"
                "It seems you don't have either installed.")
            editor_box.setToolTip(editor_tip)
        python_box = self.create_checkbox(_("Python Console"),
                                          'connect/python_console')
        ipython_box = self.create_checkbox(_("IPython Console"),
                                           'connect/ipython_console')
        ipython_box.setEnabled(QTCONSOLE_INSTALLED)

        connections_layout = QVBoxLayout()
        connections_layout.addWidget(connections_label)
        connections_layout.addWidget(editor_box)
        connections_layout.addWidget(python_box)
        connections_layout.addWidget(ipython_box)
        connections_group.setLayout(connections_layout)

        # Features group
        features_group = QGroupBox(_("Additional features"))
        math_box = self.create_checkbox(_("Render mathematical equations"),
                                        'math')
        req_sphinx = programs.is_module_installed('sphinx', '>=1.1')
        math_box.setEnabled(req_sphinx)
        if not req_sphinx:
            sphinx_ver = programs.get_module_version('sphinx')
            sphinx_tip = _("This feature requires Sphinx 1.1 or superior.")
            sphinx_tip += "\n" + _(
                "Sphinx %s is currently installed.") % sphinx_ver
            math_box.setToolTip(sphinx_tip)

        features_layout = QVBoxLayout()
        features_layout.addWidget(math_box)
        features_group.setLayout(features_layout)

        # Source code group
        sourcecode_group = QGroupBox(_("Source code"))
        wrap_mode_box = self.create_checkbox(_("Wrap lines"), 'wrap')

        sourcecode_layout = QVBoxLayout()
        sourcecode_layout.addWidget(wrap_mode_box)
        sourcecode_group.setLayout(sourcecode_layout)

        # Final layout
        vlayout = QVBoxLayout()
        vlayout.addWidget(connections_group)
        vlayout.addWidget(features_group)
        vlayout.addWidget(sourcecode_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
コード例 #55
0
    os.environ["SPYDER_DEBUG"] = "True"
    # this way of interaction suxx, because there is no feedback
    # if operation is successful

# Checking versions (among other things, this has the effect of setting the
# QT_API environment variable if this has not yet been done just above)
from spyderlib import get_versions
versions = get_versions(reporev=False)
print("03. Imported Spyder %s" % versions['spyder'])
print("    [Python %s %dbits, Qt %s, %s %s on %s]" % \
      (versions['python'], versions['bitness'], versions['qt'],
       versions['qt_api'], versions['qt_api_ver'], versions['system']))

# Check that we have the right qtpy version
from spyderlib.utils import programs
if not programs.is_module_installed('qtpy', '>=1.1.0'):
    print("")
    sys.exit("ERROR: Your qtpy version is outdated. Please install qtpy "
             "1.1.0 or higher to be able to work with Spyder!")

# --- Executing Spyder

if not options.hide_console and os.name == 'nt':
    print("0x. Enforcing parent console (Windows only)")
    sys.argv.append("--show-console")  # Windows only: show parent console

print("04. Running Spyder")
from spyderlib.app import start

time_lapse = time.time() - time_start
print("Bootstrap completed in " +
コード例 #56
0
        # If we check that we are certain we have one of these
        # types then we are less likely to generate an exception below.
            try:
                return obj.dtype.type
            except (AttributeError, RuntimeError):
                #  AttributeError: some NumPy objects have no dtype attribute
                #  RuntimeError: happens with NetCDF objects (Issue 998)
                return


#----Pandas support
PANDAS_REQVER = '>=0.13.1'
dependencies.add('pandas',  _("View and edit DataFrames and Series in the "
                              "Variable Explorer"),
                 required_version=PANDAS_REQVER)
if programs.is_module_installed('pandas', PANDAS_REQVER):
    from pandas import DataFrame, TimeSeries
else:
    DataFrame = TimeSeries = FakeObject      # analysis:ignore


#----PIL Images support
try:
    from spyderlib import pil_patch
    Image = pil_patch.Image.Image
except ImportError:
    Image = FakeObject  # analysis:ignore


#----Misc.
def address(obj):
コード例 #57
0
        # Numpy scalars all inherit from np.generic.
        # Numpy arrays all inherit from np.ndarray.
        # If we check that we are certain we have one of these
        # types then we are less likely to generate an exception below.
            try:
                return obj.dtype.type
            except (AttributeError, RuntimeError):
                #  AttributeError: some NumPy objects have no dtype attribute
                #  RuntimeError: happens with NetCDF objects (Issue 998)
                return


#==============================================================================
# Pandas support
#==============================================================================
if programs.is_module_installed('pandas', PANDAS_REQVER):
    from pandas import DataFrame, Series
else:
    DataFrame = Series = FakeObject      # analysis:ignore


#==============================================================================
# PIL Images support
#==============================================================================
try:
    from spyderlib import pil_patch
    Image = pil_patch.Image.Image
except ImportError:
    Image = FakeObject  # analysis:ignore

コード例 #58
0
    def setup_toolbar(self, exclude_private, exclude_uppercase,
                      exclude_capitalized, exclude_unsupported, autorefresh):
        """Setup toolbar"""
        self.setup_in_progress = True                          
                          
        toolbar = []

        refresh_button = create_toolbutton(self, text=_('Refresh'),
                                           icon=ima.icon('reload'),
                                           triggered=self.refresh_table)
        self.auto_refresh_button = create_toolbutton(self,
                                           text=_('Refresh periodically'),
                                           icon=ima.icon('auto_reload'),
                                           toggled=self.toggle_auto_refresh)
        self.auto_refresh_button.setChecked(autorefresh)
        load_button = create_toolbutton(self, text=_('Import data'),
                                        icon=ima.icon('fileimport'),
                                        triggered=self.import_data)
        self.save_button = create_toolbutton(self, text=_("Save data"),
                            icon=ima.icon('filesave'),
                            triggered=lambda: self.save_data(self.filename))
        self.save_button.setEnabled(False)
        save_as_button = create_toolbutton(self,
                                           text=_("Save data as..."),
                                           icon=ima.icon('filesaveas'),
                                           triggered=self.save_data)
        toolbar += [refresh_button, self.auto_refresh_button, load_button,
                    self.save_button, save_as_button]
        
        self.exclude_private_action = create_action(self,
                _("Exclude private references"),
                tip=_("Exclude references which name starts"
                            " with an underscore"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_private', state))
        self.exclude_private_action.setChecked(exclude_private)
        
        self.exclude_uppercase_action = create_action(self,
                _("Exclude all-uppercase references"),
                tip=_("Exclude references which name is uppercase"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_uppercase', state))
        self.exclude_uppercase_action.setChecked(exclude_uppercase)
        
        self.exclude_capitalized_action = create_action(self,
                _("Exclude capitalized references"),
                tip=_("Exclude references which name starts with an "
                      "uppercase character"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_capitalized', state))
        self.exclude_capitalized_action.setChecked(exclude_capitalized)
        
        self.exclude_unsupported_action = create_action(self,
                _("Exclude unsupported data types"),
                tip=_("Exclude references to unsupported data types"
                            " (i.e. which won't be handled/saved correctly)"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_unsupported', state))
        self.exclude_unsupported_action.setChecked(exclude_unsupported)
        
        options_button = create_toolbutton(self, text=_('Options'),
                                           icon=ima.icon('tooloptions'))
        toolbar.append(options_button)
        options_button.setPopupMode(QToolButton.InstantPopup)
        menu = QMenu(self)
        editor = self.editor
        actions = [self.exclude_private_action, self.exclude_uppercase_action,
                   self.exclude_capitalized_action,
                   self.exclude_unsupported_action, None,
                   editor.truncate_action]
        if is_module_installed('numpy'):
            actions.append(editor.minmax_action)
        add_actions(menu, actions)
        options_button.setMenu(menu)
        
        self.setup_in_progress = False
        
        return toolbar