本文整理汇总了Python中spyder.py3compat.to_text_string函数的典型用法代码示例。如果您正苦于以下问题:Python to_text_string函数的具体用法?Python to_text_string怎么用?Python to_text_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_text_string函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: format_measure
def format_measure(measure):
"""Get format and units for data coming from profiler task."""
# Convert to a positive value.
measure = abs(measure)
# For number of calls
if isinstance(measure, int):
return to_text_string(measure)
# For time measurements
if 1.e-9 < measure <= 1.e-6:
measure = u"{0:.2f} ns".format(measure / 1.e-9)
elif 1.e-6 < measure <= 1.e-3:
measure = u"{0:.2f} us".format(measure / 1.e-6)
elif 1.e-3 < measure <= 1:
measure = u"{0:.2f} ms".format(measure / 1.e-3)
elif 1 < measure <= 60:
measure = u"{0:.2f} sec".format(measure)
elif 60 < measure <= 3600:
m, s = divmod(measure, 3600)
if s > 60:
m, s = divmod(measure, 60)
s = to_text_string(s).split(".")[-1]
measure = u"{0:.0f}.{1:.2s} min".format(m, s)
else:
h, m = divmod(measure, 3600)
if m > 60:
m /= 60
measure = u"{0:.0f}h:{1:.0f}min".format(h, m)
return measure
开发者ID:burrbull,项目名称:spyder,代码行数:30,代码来源:profilergui.py
示例2: silent_exec_method
def silent_exec_method(self, code):
"""Silently execute a kernel method and save its reply
The methods passed here **don't** involve getting the value
of a variable but instead replies that can be handled by
ast.literal_eval.
To get a value see `get_value`
Parameters
----------
code : string
Code that contains the kernel method as part of its
string
See Also
--------
handle_exec_method : Method that deals with the reply
Note
----
This is based on the _silent_exec_callback method of
RichJupyterWidget. Therefore this is licensed BSD
"""
# Generate uuid, which would be used as an indication of whether or
# not the unique request originated from here
local_uuid = to_text_string(uuid.uuid1())
code = to_text_string(code)
msg_id = self.kernel_client.execute("", silent=True, user_expressions={local_uuid: code})
self._kernel_methods[local_uuid] = code
self._request_info["execute"][msg_id] = self._ExecutionRequest(msg_id, "silent_exec_method")
开发者ID:silentquasar,项目名称:spyder,代码行数:31,代码来源:shell.py
示例3: 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:ShenggaoZhu,项目名称:spyder,代码行数:26,代码来源:help.py
示例4: 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:0xBADCA7,项目名称:spyder,代码行数:29,代码来源:iofuncs.py
示例5: save_to_conf
def save_to_conf(self):
"""Save settings to configuration file"""
for checkbox, (option, _default) in list(self.checkboxes.items()):
self.set_option(option, checkbox.isChecked())
for radiobutton, (option, _default) in list(self.radiobuttons.items()):
self.set_option(option, radiobutton.isChecked())
for lineedit, (option, _default) in list(self.lineedits.items()):
self.set_option(option, to_text_string(lineedit.text()))
for textedit, (option, _default) in list(self.textedits.items()):
self.set_option(option, to_text_string(textedit.toPlainText()))
for spinbox, (option, _default) in list(self.spinboxes.items()):
self.set_option(option, spinbox.value())
for combobox, (option, _default) in list(self.comboboxes.items()):
data = combobox.itemData(combobox.currentIndex())
self.set_option(option, from_qvariant(data, to_text_string))
for (fontbox, sizebox), option in list(self.fontboxes.items()):
font = fontbox.currentFont()
font.setPointSize(sizebox.value())
self.set_font(font, option)
for clayout, (option, _default) in list(self.coloredits.items()):
self.set_option(option, to_text_string(clayout.lineedit.text()))
for (clayout, cb_bold, cb_italic), (option, _default) in list(self.scedits.items()):
color = to_text_string(clayout.lineedit.text())
bold = cb_bold.isChecked()
italic = cb_italic.isChecked()
self.set_option(option, (color, bold, italic))
开发者ID:impact27,项目名称:spyder,代码行数:26,代码来源:configdialog.py
示例6: 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:rlaverde,项目名称:spyder,代码行数:35,代码来源:tabs.py
示例7: create_folders_files
def create_folders_files(tmpdir, request):
"""A project directory with dirs and files for testing."""
project_dir = to_text_string(tmpdir.mkdir('project'))
destination_dir = to_text_string(tmpdir.mkdir('destination'))
top_folder = osp.join(project_dir, 'top_folder_in_proj')
if not osp.exists(top_folder):
os.mkdir(top_folder)
list_paths = []
for item in request.param:
if osp.splitext(item)[1]:
if osp.split(item)[0]:
dirs, fname = osp.split(item)
dirpath = osp.join(top_folder, dirs)
if not osp.exists(dirpath):
os.makedirs(dirpath)
item_path = osp.join(dirpath, fname)
else:
item_path = osp.join(top_folder, item)
else:
dirpath = osp.join(top_folder, item)
if not osp.exists(dirpath):
os.makedirs(dirpath)
item_path = dirpath
if not osp.isdir(item_path):
with open(item_path, 'w') as fh:
fh.write("File Path:\n" + str(item_path).replace(os.sep, '/'))
list_paths.append(item_path)
return list_paths, project_dir, destination_dir, top_folder
开发者ID:impact27,项目名称:spyder,代码行数:28,代码来源:file_fixtures.py
示例8: data
def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole or role == Qt.EditRole:
column = index.column()
row = index.row()
if column == 0:
return to_qvariant(to_text_string(self.df_index[row]))
else:
value = self.get_value(row, column-1)
if isinstance(value, float):
try:
return to_qvariant(self._format % value)
except (ValueError, TypeError):
# may happen if format = '%d' and value = NaN;
# see issue 4139
return to_qvariant(DEFAULT_FORMAT % value)
else:
try:
return to_qvariant(to_text_string(value))
except UnicodeDecodeError:
return to_qvariant(encoding.to_unicode(value))
elif role == Qt.BackgroundColorRole:
return to_qvariant(self.get_bgcolor(index))
elif role == Qt.FontRole:
return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
return to_qvariant()
开发者ID:rlaverde,项目名称:spyder,代码行数:28,代码来源:dataframeeditor.py
示例9: get_number_matches
def get_number_matches(self, pattern, source_text='', case=False,
regexp=False):
"""Get the number of matches for the searched text."""
pattern = to_text_string(pattern)
if not pattern:
return 0
if not regexp:
pattern = re.escape(pattern)
if not source_text:
source_text = to_text_string(self.toPlainText())
try:
if case:
regobj = re.compile(pattern)
else:
regobj = re.compile(pattern, re.IGNORECASE)
except sre_constants.error:
return None
number_matches = 0
for match in regobj.finditer(source_text):
number_matches += 1
return number_matches
开发者ID:pijyoi,项目名称:spyder,代码行数:26,代码来源:mixins.py
示例10: test_recent_projects_menu_action
def test_recent_projects_menu_action(projects, tmpdir):
"""
Test that the actions of the submenu 'Recent Projects' in the 'Projects'
main menu are working as expected.
Regression test for Issue #8450.
"""
recent_projects_len = len(projects.recent_projects)
# Create the directories.
path0 = to_text_string(tmpdir.mkdir('project0'))
path1 = to_text_string(tmpdir.mkdir('project1'))
path2 = to_text_string(tmpdir.mkdir('project2'))
# Open projects in path0, path1, and path2.
projects.open_project(path=path0)
projects.open_project(path=path1)
projects.open_project(path=path2)
assert (len(projects.recent_projects_actions) ==
recent_projects_len + 3 + 2)
assert projects.get_active_project().root_path == path2
# Trigger project1 in the list of Recent Projects actions.
projects.recent_projects_actions[1].trigger()
assert projects.get_active_project().root_path == path1
# Trigger project0 in the list of Recent Projects actions.
projects.recent_projects_actions[2].trigger()
assert projects.get_active_project().root_path == path0
开发者ID:impact27,项目名称:spyder,代码行数:29,代码来源:test_plugin.py
示例11: 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:ShenggaoZhu,项目名称:spyder,代码行数:32,代码来源:explorer.py
示例12: 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:ShenggaoZhu,项目名称:spyder,代码行数:25,代码来源:explorer.py
示例13: get_number_matches
def get_number_matches(self, pattern, source_text='', case=False):
"""Get the number of matches for the searched text."""
pattern = to_text_string(pattern)
if not pattern:
return 0
if not source_text:
if WEBENGINE:
self.page().toPlainText(self.set_source_text)
source_text = to_text_string(self.source_text)
else:
source_text = to_text_string(
self.page().mainFrame().toPlainText())
try:
if case:
regobj = re.compile(pattern)
else:
regobj = re.compile(pattern, re.IGNORECASE)
except sre_constants.error:
return
number_matches = 0
for match in regobj.finditer(source_text):
number_matches += 1
return number_matches
开发者ID:rlaverde,项目名称:spyder,代码行数:25,代码来源:browser.py
示例14: 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:ShenggaoZhu,项目名称:spyder,代码行数:28,代码来源:explorer.py
示例15: 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,
css_path=self.css_path)
html_text = sphinxify(doc['docstring'], context)
if doc['docstring'] == '':
if any([doc['name'], doc['argspec'], doc['note']]):
msg = _("No further documentation available")
html_text += '<div class="hr"></div>'
else:
msg = _("No documentation available")
html_text += '<div id="doc-warning">%s</div>' % msg
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:burrbull,项目名称:spyder,代码行数:30,代码来源:sphinxthread.py
示例16: goto_line
def goto_line(self, line, column=0, end_column=0, move=True, word=''):
"""
Moves the text cursor to the specified position.
:param line: Number of the line to go to (0 based)
:param column: Optional column number. Default is 0 (start of line).
:param move: True to move the cursor. False will return the cursor
without setting it on the editor.
:param word: Highlight the word, when moving to the line.
:return: The new text cursor
:rtype: QtGui.QTextCursor
"""
line = min(line, self.line_count())
text_cursor = self._move_cursor_to(line)
if column:
text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor,
column)
if end_column:
text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor,
end_column)
if move:
block = text_cursor.block()
self.unfold_if_colapsed(block)
self._editor.setTextCursor(text_cursor)
if self._editor.isVisible():
self._editor.centerCursor()
else:
self._editor.focus_in.connect(
self._editor.center_cursor_on_next_focus)
if word and to_text_string(word) in to_text_string(block.text()):
self._editor.find(word, QTextDocument.FindCaseSensitively)
return text_cursor
开发者ID:impact27,项目名称:spyder,代码行数:33,代码来源:editor.py
示例17: get_options
def get_options(self, all=False):
# Getting options
self.search_text.lineEdit().setStyleSheet("")
self.exclude_pattern.lineEdit().setStyleSheet("")
utext = to_text_string(self.search_text.currentText())
if not utext:
return
try:
texts = [(utext.encode('utf-8'), 'utf-8')]
except UnicodeEncodeError:
texts = []
for enc in self.supported_encodings:
try:
texts.append((utext.encode(enc), enc))
except UnicodeDecodeError:
pass
text_re = self.edit_regexp.isChecked()
exclude = to_text_string(self.exclude_pattern.currentText())
exclude_re = self.exclude_regexp.isChecked()
case_sensitive = self.case_button.isChecked()
python_path = False
if not case_sensitive:
texts = [(text[0].lower(), text[1]) for text in texts]
file_search = self.path_selection_combo.is_file_search()
path = self.path_selection_combo.get_current_searchpath()
# Finding text occurrences
if not exclude_re:
exclude = fnmatch.translate(exclude)
else:
try:
exclude = re.compile(exclude)
except Exception:
exclude_edit = self.exclude_pattern.lineEdit()
exclude_edit.setStyleSheet(self.REGEX_INVALID)
return None
if text_re:
try:
texts = [(re.compile(x[0]), x[1]) for x in texts]
except Exception:
self.search_text.lineEdit().setStyleSheet(self.REGEX_INVALID)
return None
if all:
search_text = [to_text_string(self.search_text.itemText(index))
for index in range(self.search_text.count())]
exclude = [to_text_string(self.exclude_pattern.itemText(index))
for index in range(self.exclude_pattern.count())]
path_history = self.path_selection_combo.get_external_paths()
exclude_idx = self.exclude_pattern.currentIndex()
more_options = self.more_options.isChecked()
return (search_text, text_re, [],
exclude, exclude_idx, exclude_re,
python_path, more_options, case_sensitive, path_history)
else:
return (path, file_search, exclude, texts, text_re, case_sensitive)
开发者ID:0xBADCA7,项目名称:spyder,代码行数:60,代码来源:findinfiles.py
示例18: test_fix_indentation
def test_fix_indentation(code_editor_indent_bot):
"""Test fix_indentation() method."""
editor, qtbot = code_editor_indent_bot
# Contains tabs.
original = ("\t\n"
"class a():\t\n"
"\tself.b = 1\n"
"\tprint(self.b)\n"
"\n"
)
# Fix indentation replaces tabs with indent_chars spaces.
fixed = (" \n"
"class a(): \n"
" self.b = 1\n"
" print(self.b)\n"
"\n"
)
editor.set_text(original)
editor.fix_indentation()
assert to_text_string(editor.toPlainText()) == fixed
assert editor.document().isModified()
# Test that undo/redo works - issue 1754.
editor.undo()
assert to_text_string(editor.toPlainText()) == original
assert not editor.document().isModified()
editor.redo()
assert to_text_string(editor.toPlainText()) == fixed
assert editor.document().isModified()
开发者ID:burrbull,项目名称:spyder,代码行数:28,代码来源:test_indentation.py
示例19: 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.removed_tree.connect(self.main.editor.removed_tree)
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:ShenggaoZhu,项目名称:spyder,代码行数:26,代码来源:explorer.py
示例20: 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:jitseniesen,项目名称:spyder,代码行数:29,代码来源:mixins.py
注:本文中的spyder.py3compat.to_text_string函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论