当前位置: 首页>>代码示例>>Python>>正文


Python py3compat.to_text_string函数代码示例

本文整理汇总了Python中spyderlib.py3compat.to_text_string函数的典型用法代码示例。如果您正苦于以下问题:Python to_text_string函数的具体用法?Python to_text_string怎么用?Python to_text_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了to_text_string函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run_script_in_current_client

 def run_script_in_current_client(self, filename, wdir, args, debug):
     """Run script in current client, if any"""
     norm = lambda text: remove_backslashes(to_text_string(text))
     client = self.get_current_client()
     if client is not None:
         # Internal kernels, use runfile
         if client.kernel_widget_id is not None:
             line = "%s('%s'" % ('debugfile' if debug else 'runfile',
                                 norm(filename))
             if args:
                 line += ", args='%s'" % norm(args)
             if wdir:
                 line += ", wdir='%s'" % norm(wdir)
             line += ")"
         else: # External kernels, use %run
             line = "%run "
             if debug:
                 line += "-d "
             line += "\"%s\"" % to_text_string(filename)
             if args:
                 line += " %s" % norm(args)
         self.execute_python_code(line)
         self.visibility_changed(True)
         self.raise_()
     else:
         #XXX: not sure it can really happen
         QMessageBox.warning(self, _('Warning'),
             _("No IPython console is currently available to run <b>%s</b>."
               "<br><br>Please open a new one and try again."
               ) % osp.basename(filename), QMessageBox.Ok)
开发者ID:Poneyo,项目名称:spyderlib,代码行数:30,代码来源:ipythonconsole.py

示例2: run

    def run(self):
        html_text = self.html_text_no_doc
        doc = self.doc
        if doc is not None:
            if type(doc) is dict and 'docstring' in doc.keys():
                try:
                    context = generate_context(name=doc['name'],
                                               argspec=doc['argspec'],
                                               note=doc['note'],
                                               math=self.math_option,
                                               img_path=self.img_path)
                    html_text = sphinxify(doc['docstring'], context)
                    if doc['docstring'] == '':
                        html_text += '<div class="hr"></div>'
                        html_text += self.html_text_no_doc

                except Exception as error:
                    self.error_msg.emit(to_text_string(error))
                    return
            elif self.context is not None:
                try:
                    html_text = sphinxify(doc, self.context)
                except Exception as error:
                    self.error_msg.emit(to_text_string(error))
                    return
        self.html_ready.emit(html_text)
开发者ID:dzosz,项目名称:spyder,代码行数:26,代码来源:help.py

示例3: _find_parenthesis

 def _find_parenthesis(self, position, forward=True):
     """ If 'forward' is True (resp. False), proceed forwards
         (resp. backwards) through the line that contains 'position' until an
         unmatched closing (resp. opening) parenthesis is found. Returns a
         tuple containing the position of this parenthesis (or -1 if it is
         not found) and the number commas (at depth 0) found along the way.
     """
     commas = depth = 0
     document = self._text_edit.document()
     char = to_text_string(document.characterAt(position))
     # Search until a match is found or a non-printable character is
     # encountered.
     while category(char) != 'Cc' and position > 0:
         if char == ',' and depth == 0:
             commas += 1
         elif char == ')':
             if forward and depth == 0:
                 break
             depth += 1
         elif char == '(':
             if not forward and depth == 0:
                 break
             depth -= 1
         position += 1 if forward else -1
         char = to_text_string(document.characterAt(position))
     else:
         position = -1
     return position, commas
开发者ID:AminJamalzadeh,项目名称:spyder,代码行数:28,代码来源:calltip.py

示例4: find_multiline_pattern

 def find_multiline_pattern(self, regexp, cursor, findflag):
     """Reimplement QTextDocument's find method
     
     Add support for *multiline* regular expressions"""
     pattern = to_text_string(regexp.pattern())
     text = to_text_string(self.toPlainText())
     try:
         regobj = re.compile(pattern)
     except sre_constants.error:
         return
     if findflag & QTextDocument.FindBackward:
         # Find backward
         offset = min([cursor.selectionEnd(), cursor.selectionStart()])
         text = text[:offset]
         matches = [_m for _m in regobj.finditer(text, 0, offset)]
         if matches:
             match = matches[-1]
         else:
             return
     else:
         # Find forward
         offset = max([cursor.selectionEnd(), cursor.selectionStart()])
         match = regobj.search(text, offset)
     if match:
         pos1, pos2 = match.span()
         fcursor = self.textCursor()
         fcursor.setPosition(pos1)
         fcursor.setPosition(pos2, QTextCursor.KeepAnchor)
         return fcursor
开发者ID:arvindchari88,项目名称:newGitTest,代码行数:29,代码来源:mixins.py

示例5: update_browse_tabs_menu

 def update_browse_tabs_menu(self):
     """Update browse tabs menu"""
     self.browse_tabs_menu.clear()
     names = []
     dirnames = []
     for index in range(self.count()):
         if self.menu_use_tooltips:
             text = to_text_string(self.tabToolTip(index))
         else:
             text = to_text_string(self.tabText(index))
         names.append(text)
         if osp.isfile(text):
             # Testing if tab names are filenames
             dirnames.append(osp.dirname(text))
     offset = None
     
     # If tab names are all filenames, removing common path:
     if len(names) == len(dirnames):
         common = get_common_path(dirnames)
         if common is None:
             offset = None
         else:
             offset = len(common)+1
             if offset <= 3:
                 # Common path is not a path but a drive letter...
                 offset = None
             
     for index, text in enumerate(names):
         tab_action = create_action(self, text[offset:],
                                    icon=self.tabIcon(index),
                                    toggled=lambda state, index=index:
                                            self.setCurrentIndex(index),
                                    tip=self.tabToolTip(index))
         tab_action.setChecked(index == self.currentIndex())
         self.browse_tabs_menu.addAction(tab_action)
开发者ID:MarvinLiu0810,项目名称:spyder,代码行数:35,代码来源:tabs.py

示例6: rename_file

 def rename_file(self, fname):
     """Rename file"""
     path, valid = QInputDialog.getText(self, _("Rename"), _("New name:"), QLineEdit.Normal, osp.basename(fname))
     if valid:
         path = osp.join(osp.dirname(fname), to_text_string(path))
         if path == fname:
             return
         if osp.exists(path):
             if (
                 QMessageBox.warning(
                     self,
                     _("Rename"),
                     _("Do you really want to rename <b>%s</b> and " "overwrite the existing file <b>%s</b>?")
                     % (osp.basename(fname), osp.basename(path)),
                     QMessageBox.Yes | QMessageBox.No,
                 )
                 == QMessageBox.No
             ):
                 return
         try:
             misc.rename_file(fname, path)
             self.parent_widget.renamed.emit(fname, path)
             return path
         except EnvironmentError as error:
             QMessageBox.critical(
                 self,
                 _("Rename"),
                 _("<b>Unable to rename file <i>%s</i></b>" "<br><br>Error message:<br>%s")
                 % (osp.basename(fname), to_text_string(error)),
             )
开发者ID:sonofeft,项目名称:spyder,代码行数:30,代码来源:explorer.py

示例7: create_new_folder

 def create_new_folder(self, current_path, title, subtitle, is_package):
     """Create new folder"""
     if current_path is None:
         current_path = ""
     if osp.isfile(current_path):
         current_path = osp.dirname(current_path)
     name, valid = QInputDialog.getText(self, title, subtitle, QLineEdit.Normal, "")
     if valid:
         dirname = osp.join(current_path, to_text_string(name))
         try:
             os.mkdir(dirname)
         except EnvironmentError as error:
             QMessageBox.critical(
                 self,
                 title,
                 _("<b>Unable " "to create folder <i>%s</i></b>" "<br><br>Error message:<br>%s")
                 % (dirname, to_text_string(error)),
             )
         finally:
             if is_package:
                 fname = osp.join(dirname, "__init__.py")
                 try:
                     with open(fname, "wb") as f:
                         f.write(to_binary_string("#"))
                     return dirname
                 except EnvironmentError as error:
                     QMessageBox.critical(
                         self,
                         title,
                         _("<b>Unable " "to create file <i>%s</i></b>" "<br><br>Error message:<br>%s")
                         % (fname, to_text_string(error)),
                     )
开发者ID:sonofeft,项目名称:spyder,代码行数:32,代码来源:explorer.py

示例8: register_plugin

    def register_plugin(self):
        """Register plugin in Spyder's main window"""
        self.main.add_dockwidget(self)
        self.edit.connect(self.main.editor.load)
        self.removed.connect(self.main.editor.removed)
        self.renamed.connect(self.main.editor.renamed)
        self.main.editor.open_dir.connect(self.chdir)
        self.create_module.connect(self.main.editor.new)
        self.run.connect(
                     lambda fname:
                     self.main.open_external_console(to_text_string(fname),
                                         osp.dirname(to_text_string(fname)),
                                         '', False, False, True, '', False))
        # Signal "set_explorer_cwd(QString)" will refresh only the
        # contents of path passed by the signal in explorer:
        self.main.workingdirectory.set_explorer_cwd.connect(
                     lambda directory: self.refresh_plugin(new_path=directory,
                                                           force_current=True))
        self.open_dir.connect(
                     lambda dirname:
                     self.main.workingdirectory.chdir(dirname,
                                                      refresh_explorer=False))

        self.sig_open_file.connect(self.main.open_file)
        self.sig_new_file.connect(lambda t: self.main.editor.new(text=t))
开发者ID:ChunHungLiu,项目名称:spyder,代码行数:25,代码来源:explorer.py

示例9: chdir

 def chdir(self, directory=None, browsing_history=False):
     """Set directory as working directory"""
     if directory is not None:
         directory = osp.abspath(to_text_string(directory))
     if browsing_history:
         directory = self.history[self.histindex]
     elif directory in self.history:
         self.histindex = self.history.index(directory)
     else:
         if self.histindex is None:
             self.history = []
         else:
             self.history = self.history[: self.histindex + 1]
         if len(self.history) == 0 or (self.history and self.history[-1] != directory):
             self.history.append(directory)
         self.histindex = len(self.history) - 1
     directory = to_text_string(directory)
     if PY2:
         PermissionError = OSError
     try:
         os.chdir(directory)
         self.parent_widget.open_dir.emit(directory)
         self.refresh(new_path=directory, force_current=True)
     except PermissionError:
         QMessageBox.critical(
             self.parent_widget, "Error", _("You don't have the right permissions to " "open this directory")
         )
开发者ID:sonofeft,项目名称:spyder,代码行数:27,代码来源:explorer.py

示例10: start

    def start(self, wdir=None, args=None, pythonpath=None):
        filename = to_text_string(self.filecombo.currentText())
        if wdir is None:
            wdir = self._last_wdir
            if wdir is None:
                wdir = osp.basename(filename)
        if args is None:
            args = self._last_args
            if args is None:
                args = []
        if pythonpath is None:
            pythonpath = self._last_pythonpath
        self._last_wdir = wdir
        self._last_args = args
        self._last_pythonpath = pythonpath
        
        self.datelabel.setText(_('Profiling, please wait...'))
        
        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.process.setWorkingDirectory(wdir)
        self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
                     self.read_output)
        self.connect(self.process, SIGNAL("readyReadStandardError()"),
                     lambda: self.read_output(error=True))
        self.connect(self.process,
                     SIGNAL("finished(int,QProcess::ExitStatus)"),
                     self.finished)
        self.connect(self.stop_button, SIGNAL("clicked()"), self.process.kill)

        if pythonpath is not None:
            env = [to_text_string(_pth)
                   for _pth in self.process.systemEnvironment()]
            baseshell.add_pathlist_to_PYTHONPATH(env, pythonpath)
            self.process.setEnvironment(env)
        
        self.output = ''
        self.error_output = ''
        
        p_args = ['-m', 'cProfile', '-o', self.DATAPATH]
        if os.name == 'nt':
            # On Windows, one has to replace backslashes by slashes to avoid 
            # confusion with escape characters (otherwise, for example, '\t' 
            # will be interpreted as a tabulation):
            p_args.append(osp.normpath(filename).replace(os.sep, '/'))
        else:
            p_args.append(filename)
        if args:
            p_args.extend(shell_split(args))
        executable = sys.executable
        if executable.endswith("spyder.exe"):
            # py2exe distribution
            executable = "python.exe"
        self.process.start(executable, p_args)
        
        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, _("Error"),
                                 _("Process failed to start"))
开发者ID:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:60,代码来源:profilergui.py

示例11: value_to_display

def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    if minmax and isinstance(value, (ndarray, MaskedArray)):
        if value.size == 0:
            return repr(value)
        try:
            return 'Min: %r\nMax: %r' % (value.min(), value.max())
        except TypeError:
            pass
        except ValueError:
            # Happens when one of the array cell contains a sequence
            pass
    if isinstance(value, Image):
        return '%s  Mode: %s' % (address(value), value.mode)
    if isinstance(value, DataFrame):
        cols = value.columns
        cols = [to_text_string(c) for c in cols]
        return 'Column names: ' + ', '.join(list(cols))
    if is_binary_string(value):
        try:
            value = to_text_string(value, 'utf8')
        except:
            pass
    if not is_text_string(value):
        if isinstance(value, (list, tuple, dict, set)):
            value = CollectionsRepr.repr(value)
        else:
            value = repr(value)
    if truncate and len(value) > trunc_len:
        value = value[:trunc_len].rstrip() + ' ...'
    return value
开发者ID:jayitb,项目名称:Spyderplugin_ratelaws,代码行数:31,代码来源:dicteditorutils.py

示例12: setup

 def setup(self):
     iofuncs = self.get_internal_funcs() + self.get_3rd_party_funcs()
     load_extensions = {}
     save_extensions = {}
     load_funcs = {}
     save_funcs = {}
     load_filters = []
     save_filters = []
     load_ext = []
     for ext, name, loadfunc, savefunc in iofuncs:
         filter_str = to_text_string(name + " (*%s)" % ext)
         if loadfunc is not None:
             load_filters.append(filter_str)
             load_extensions[filter_str] = ext
             load_funcs[ext] = loadfunc
             load_ext.append(ext)
         if savefunc is not None:
             save_extensions[filter_str] = ext
             save_filters.append(filter_str)
             save_funcs[ext] = savefunc
     load_filters.insert(0, to_text_string(_("Supported files") + " (*" + " *".join(load_ext) + ")"))
     load_filters.append(to_text_string(_("All files (*.*)")))
     self.load_filters = "\n".join(load_filters)
     self.save_filters = "\n".join(save_filters)
     self.load_funcs = load_funcs
     self.save_funcs = save_funcs
     self.load_extensions = load_extensions
     self.save_extensions = save_extensions
开发者ID:ymarfoq,项目名称:outilACVDesagregation,代码行数:28,代码来源:iofuncs.py

示例13: replace_find

 def replace_find(self):
     """Replace and find"""
     if self.editor is not None:
         replace_text = to_text_string(self.replace_text.currentText())
         search_text = to_text_string(self.search_text.currentText())
         pattern = search_text if self.re_button.isChecked() else None
         case = self.case_button.isChecked()
         first = True
         cursor = None
         while True:
             if first:
                 # First found
                 seltxt = to_text_string(self.editor.get_selected_text())
                 cmptxt1 = search_text if case else search_text.lower()
                 cmptxt2 = seltxt if case else seltxt.lower()
                 if self.editor.has_selected_text() and cmptxt1 == cmptxt2:
                     # Text was already found, do nothing
                     pass
                 else:
                     if not self.find(changed=False, forward=True, rehighlight=False):
                         break
                 first = False
                 wrapped = False
                 position = self.editor.get_position("cursor")
                 position0 = position
                 cursor = self.editor.textCursor()
                 cursor.beginEditBlock()
             else:
                 position1 = self.editor.get_position("cursor")
                 if is_position_inf(position1, position0 + len(replace_text) - len(search_text) + 1):
                     # Identify wrapping even when the replace string
                     # includes part of the search string
                     wrapped = True
                 if wrapped:
                     if position1 == position or is_position_sup(position1, position):
                         # Avoid infinite loop: replace string includes
                         # part of the search string
                         break
                 if position1 == position0:
                     # Avoid infinite loop: single found occurence
                     break
                 position0 = position1
             if pattern is None:
                 cursor.removeSelectedText()
                 cursor.insertText(replace_text)
             else:
                 seltxt = to_text_string(cursor.selectedText())
                 cursor.removeSelectedText()
                 cursor.insertText(re.sub(pattern, replace_text, seltxt))
             if self.find_next():
                 found_cursor = self.editor.textCursor()
                 cursor.setPosition(found_cursor.selectionStart(), QTextCursor.MoveAnchor)
                 cursor.setPosition(found_cursor.selectionEnd(), QTextCursor.KeepAnchor)
             else:
                 break
             if not self.all_check.isChecked():
                 break
         self.all_check.setCheckState(Qt.Unchecked)
         if cursor is not None:
             cursor.endEditBlock()
开发者ID:ftsiadimos,项目名称:spyder,代码行数:60,代码来源:findreplace.py

示例14: _qfiledialog_wrapper

def _qfiledialog_wrapper(attr, parent=None, caption='', basedir='',
                         filters='', selectedfilter='', options=None):
    if options is None:
        options = QFileDialog.Options(0)
    try:
        # PyQt <v4.6 (API #1)
        from spyderlib.qt.QtCore import QString
    except ImportError:
        # PySide or PyQt >=v4.6
        QString = None  # analysis:ignore
    tuple_returned = True
    try:
        # PyQt >=v4.6
        func = getattr(QFileDialog, attr+'AndFilter')
    except AttributeError:
        # PySide or PyQt <v4.6
        func = getattr(QFileDialog, attr)
        if QString is not None:
            selectedfilter = QString()
            tuple_returned = False
    
    # Calling QFileDialog static method
    if sys.platform == "win32":
        # On Windows platforms: redirect standard outputs
        _temp1, _temp2 = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = None, None
    try:
        result = func(parent, caption, basedir,
                      filters, selectedfilter, options)
    except TypeError:
        # The selectedfilter option (`initialFilter` in Qt) has only been 
        # introduced in Jan. 2010 for PyQt v4.7, that's why we handle here 
        # the TypeError exception which will be raised with PyQt v4.6
        # (see Issue 960 for more details)
        result = func(parent, caption, basedir, filters, options)
    finally:
        if sys.platform == "win32":
            # On Windows platforms: restore standard outputs
            sys.stdout, sys.stderr = _temp1, _temp2
            
    # Processing output
    if tuple_returned:
        # PySide or PyQt >=v4.6
        output, selectedfilter = result
    else:
        # PyQt <v4.6 (API #1)
        output = result
    if QString is not None:
        # PyQt API #1: conversions needed from QString/QStringList
        selectedfilter = to_text_string(selectedfilter)
        if isinstance(output, QString):
            # Single filename
            output = to_text_string(output)
        else:
            # List of filenames
            output = [to_text_string(fname) for fname in output]
            
    # Always returns the tuple (output, selectedfilter)
    return output, selectedfilter
开发者ID:arvindchari88,项目名称:newGitTest,代码行数:59,代码来源:compat.py

示例15: is_cell_separator

 def is_cell_separator(self, cursor=None, block=None):
     """Return True if cursor (or text block) is on a block separator"""
     assert cursor is not None or block is not None
     if cursor is not None:
         cursor0 = QTextCursor(cursor)
         cursor0.select(QTextCursor.BlockUnderCursor)
         text = to_text_string(cursor0.selectedText())
     else:
         text = to_text_string(block.text())
     return text.lstrip().startswith(CELL_SEPARATORS)
开发者ID:jromang,项目名称:spyderlib,代码行数:10,代码来源:base.py


注:本文中的spyderlib.py3compat.to_text_string函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。