本文整理汇总了Python中prompt_toolkit.CommandLineInterface.request_redraw方法的典型用法代码示例。如果您正苦于以下问题:Python CommandLineInterface.request_redraw方法的具体用法?Python CommandLineInterface.request_redraw怎么用?Python CommandLineInterface.request_redraw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类prompt_toolkit.CommandLineInterface
的用法示例。
在下文中一共展示了CommandLineInterface.request_redraw方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PGCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import request_redraw [as 别名]
#.........这里部分代码省略.........
total += end - start
mutating = mutating or is_mutating(status)
except KeyboardInterrupt:
# Restart connection to the database
pgexecute.connect()
logger.debug("cancelled query, sql: %r", document.text)
click.secho("cancelled query", err=True, fg='red')
except NotImplementedError:
click.secho('Not Yet Implemented.', fg="yellow")
except OperationalError as e:
reconnect = True
if ('server closed the connection' in utf8tounicode(
e.args[0])):
reconnect = click.prompt(
'Connection reset. Reconnect (Y/n)',
show_default=False,
type=bool,
default=True)
if reconnect:
try:
pgexecute.connect()
click.secho(
'Reconnected!\nTry the command again.',
fg='green')
except OperationalError as e:
click.secho(str(e), err=True, fg='red')
else:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
click.secho(str(e), err=True, fg='red')
except Exception as e:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
click.secho(str(e), err=True, fg='red')
else:
try:
click.echo_via_pager('\n'.join(output))
except KeyboardInterrupt:
pass
if self.pgspecial.timing_enabled:
print('Command Time: %0.03fs' % duration)
print('Format Time: %0.03fs' % total)
# Refresh the table names and column names if necessary.
if need_completion_refresh(document.text):
self.refresh_completions()
# Refresh search_path to set default schema.
if need_search_path_refresh(document.text):
logger.debug('Refreshing search path')
with self._completer_lock:
self.completer.set_search_path(pgexecute.search_path())
logger.debug('Search path: %r', self.completer.search_path)
query = Query(document.text, successful, mutating)
self.query_history.append(query)
except EOFError:
print('Goodbye!')
finally: # Reset the less opts back to original.
logger.debug('Restoring env var LESS to %r.', original_less_opts)
os.environ['LESS'] = original_less_opts
def adjust_less_opts(self):
less_opts = os.environ.get('LESS', '')
self.logger.debug('Original value for LESS env var: %r', less_opts)
os.environ['LESS'] = '-SRXF'
return less_opts
def refresh_completions(self):
self.completion_refresher.refresh(self.pgexecute, self.pgspecial,
self._on_completions_refreshed)
return [(None, None, None,
'Auto-completion refresh started in the background.')]
def _on_completions_refreshed(self, new_completer):
self._swap_completer_objects(new_completer)
if self.cli:
# After refreshing, redraw the CLI to clear the statusbar
# "Refreshing completions..." indicator
self.cli.request_redraw()
def _swap_completer_objects(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When pgcli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before trying the replace the completer object in cli.
if self.cli:
self.cli.current_buffer.completer = new_completer
def get_completions(self, text, cursor_positition):
with self._completer_lock:
return self.completer.get_completions(
Document(text=text, cursor_position=cursor_positition), None)
示例2: MyCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import request_redraw [as 别名]
#.........这里部分代码省略.........
self.output(str(e), err=True, fg='red')
continue # If reconnection failed, don't proceed further.
else: # If user chooses not to reconnect, don't proceed further.
continue
else:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
self.output(str(e), err=True, fg='red')
except Exception as e:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
self.output(str(e), err=True, fg='red')
else:
try:
if special.is_pager_enabled():
self.output_via_pager('\n'.join(output))
else:
self.output('\n'.join(output))
except KeyboardInterrupt:
pass
if special.is_timing_enabled():
self.output('Time: %0.03fs' % total)
# Refresh the table names and column names if necessary.
if need_completion_refresh(document.text):
self.refresh_completions(
reset=need_completion_reset(document.text))
finally:
if self.logfile is False:
self.output("Warning: This query was not logged.", err=True, fg='red')
query = Query(document.text, successful, mutating)
self.query_history.append(query)
except EOFError:
self.output('Goodbye!')
def output(self, text, **kwargs):
if self.logfile:
self.logfile.write(utf8tounicode(text))
self.logfile.write('\n')
click.secho(text, **kwargs)
def output_via_pager(self, text):
if self.logfile:
self.logfile.write(text)
self.logfile.write('\n')
click.echo_via_pager(text)
def configure_pager(self):
# Provide sane defaults for less.
os.environ['LESS'] = '-SRXF'
cnf = self.read_my_cnf_files(self.cnf_files, ['pager', 'skip-pager'])
if cnf['pager']:
special.set_pager(cnf['pager'])
if cnf['skip-pager']:
special.disable_pager()
def refresh_completions(self, reset=False):
if reset:
with self._completer_lock:
self.completer.reset_completions()
self.completion_refresher.refresh(self.sqlexecute,
self._on_completions_refreshed)
return [(None, None, None,
'Auto-completion refresh started in the background.')]
def _on_completions_refreshed(self, new_completer):
self._swap_completer_objects(new_completer)
if self.cli:
# After refreshing, redraw the CLI to clear the statusbar
# "Refreshing completions..." indicator
self.cli.request_redraw()
def _swap_completer_objects(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When mycli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before trying the replace the completer object in cli.
if self.cli:
self.cli.current_buffer.completer = new_completer
def get_completions(self, text, cursor_positition):
with self._completer_lock:
return self.completer.get_completions(
Document(text=text, cursor_position=cursor_positition), None)
def get_prompt(self, string):
sqlexecute = self.sqlexecute
string = string.replace('\\u', sqlexecute.user or '(none)')
string = string.replace('\\h', sqlexecute.host or '(none)')
string = string.replace('\\d', sqlexecute.dbname or '(none)')
string = string.replace('\\t', sqlexecute.server_type()[0] or 'mycli')
string = string.replace('\\n', "\n")
return string
示例3: MyCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import request_redraw [as 别名]
#.........这里部分代码省略.........
logger.debug("Reconnected successfully.")
self.output("Reconnected!\nTry the command again.", fg="green")
except OperationalError as e:
logger.debug("Reconnect failed. e: %r", e)
self.output(str(e), err=True, fg="red")
continue # If reconnection failed, don't proceed further.
else: # If user chooses not to reconnect, don't proceed further.
continue
else:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
self.output(str(e), err=True, fg="red")
except Exception as e:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
self.output(str(e), err=True, fg="red")
else:
try:
if special.is_pager_enabled():
self.output_via_pager("\n".join(output))
else:
self.output("\n".join(output))
except KeyboardInterrupt:
pass
if special.is_timing_enabled():
self.output("Time: %0.03fs" % total)
# Refresh the table names and column names if necessary.
if need_completion_refresh(document.text):
self.refresh_completions(reset=need_completion_reset(document.text))
finally:
if self.logfile is False:
self.output("Warning: This query was not logged.", err=True, fg="red")
query = Query(document.text, successful, mutating)
self.query_history.append(query)
except EOFError:
self.output("Goodbye!")
def output(self, text, **kwargs):
if self.logfile:
self.logfile.write(utf8tounicode(text))
self.logfile.write("\n")
click.secho(text, **kwargs)
def output_via_pager(self, text):
if self.logfile:
self.logfile.write(text)
self.logfile.write("\n")
click.echo_via_pager(text)
def configure_pager(self):
# Provide sane defaults for less.
os.environ["LESS"] = "-RXF"
cnf = self.read_my_cnf_files(self.cnf_files, ["pager", "skip-pager"])
if cnf["pager"]:
special.set_pager(cnf["pager"])
if cnf["skip-pager"]:
special.disable_pager()
def refresh_completions(self, reset=False):
if reset:
with self._completer_lock:
self.completer.reset_completions()
self.completion_refresher.refresh(self.sqlexecute, self._on_completions_refreshed)
return [(None, None, None, "Auto-completion refresh started in the background.")]
def _on_completions_refreshed(self, new_completer):
self._swap_completer_objects(new_completer)
if self.cli:
# After refreshing, redraw the CLI to clear the statusbar
# "Refreshing completions..." indicator
self.cli.request_redraw()
def _swap_completer_objects(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When mycli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before trying the replace the completer object in cli.
if self.cli:
self.cli.current_buffer.completer = new_completer
def get_completions(self, text, cursor_positition):
with self._completer_lock:
return self.completer.get_completions(Document(text=text, cursor_position=cursor_positition), None)
def get_prompt(self, string):
sqlexecute = self.sqlexecute
string = string.replace("\\u", sqlexecute.user or "(none)")
string = string.replace("\\h", sqlexecute.host or "(none)")
string = string.replace("\\d", sqlexecute.dbname or "(none)")
string = string.replace("\\t", sqlexecute.server_type()[0] or "mycli")
string = string.replace("\\n", "\n")
return string
示例4: VCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import request_redraw [as 别名]
#.........这里部分代码省略.........
vexecute.connect()
logger.debug("cancelled query, sql: %r", document.text)
click.secho("cancelled query", err=True, fg='red')
except NotImplementedError:
click.secho('Not Yet Implemented.', fg="yellow")
except errors.ConnectionError as e:
reconnect = True
if ('Connection is closed' in utf8tounicode(e.args[0])):
reconnect = click.prompt('Connection reset. Reconnect (Y/n)',
show_default=False, type=bool, default=True)
if reconnect:
try:
vexecute.connect()
click.secho('Reconnected!\nTry the command again.', fg='green')
except errors.DatabaseError as e:
click.secho(str(e), err=True, fg='red')
else:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
click.secho(str(e), err=True, fg='red')
except Exception as e:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
click.secho(str(e), err=True, fg='red')
else:
successful = True
if stdout_output:
output = '\n'.join(stdout_output)
try:
click.echo_via_pager(output)
except KeyboardInterrupt:
pass
if file_output:
try:
file_output.flush()
except KeyboardInterrupt:
pass
if self.vspecial.timing_enabled:
print('Time: command: %0.03fs, total: %0.03fs' % (duration, total))
# Refresh the table names and column names if necessary.
if need_completion_refresh(document.text):
self.refresh_completions(need_completion_reset(document.text))
# Refresh search_path to set default schema.
if need_search_path_refresh(document.text):
logger.debug('Refreshing search path')
with self._completer_lock:
self.completer.set_search_path(vexecute.search_path())
logger.debug('Search path: %r', self.completer.search_path)
query = Query(document.text, successful, mutating)
self.query_history.append(query)
except EOFError:
print ('Goodbye!')
finally: # Reset the less opts back to original.
logger.debug('Restoring env var LESS to %r.', original_less_opts)
os.environ['LESS'] = original_less_opts
def adjust_less_opts(self):
less_opts = os.environ.get('LESS', '')
self.logger.debug('Original value for LESS env var: %r', less_opts)
os.environ['LESS'] = '-RXF'
return less_opts
def refresh_completions(self, reset=False):
if reset:
with self._completer_lock:
self.completer.reset_completions()
self.completion_refresher.refresh(self.vexecute, self.vspecial,
self._on_completions_refreshed)
return [(None, None, None,
'Auto-completion refresh started in the background.', True)]
def _on_completions_refreshed(self, new_completer):
self._swap_completer_objects(new_completer)
if self.cli:
# After refreshing, redraw the CLI to clear the statusbar
# "Refreshing completions..." indicator
self.cli.request_redraw()
def _swap_completer_objects(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When pgcli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before trying the replace the completer object in cli.
if self.cli:
self.cli.current_buffer.completer = new_completer
def get_completions(self, text, cursor_positition):
with self._completer_lock:
return self.completer.get_completions(
Document(text=text, cursor_position=cursor_positition), None)
示例5: MyCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import request_redraw [as 别名]
#.........这里部分代码省略.........
else:
self.explicit_pager = False
if cnf['skip-pager'] or not self.config['main'].as_bool('enable_pager'):
special.disable_pager()
def refresh_completions(self, reset=False):
if reset:
with self._completer_lock:
self.completer.reset_completions()
self.completion_refresher.refresh(
self.sqlexecute, self._on_completions_refreshed,
{'smart_completion': self.smart_completion,
'supported_formats': self.formatter.supported_formats,
'keyword_casing': self.completer.keyword_casing})
return [(None, None, None,
'Auto-completion refresh started in the background.')]
def _on_completions_refreshed(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When mycli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before trying the replace the completer object in cli.
if self.cli:
self.cli.current_buffer.completer = new_completer
if self.cli:
# After refreshing, redraw the CLI to clear the statusbar
# "Refreshing completions..." indicator
self.cli.request_redraw()
def get_completions(self, text, cursor_positition):
with self._completer_lock:
return self.completer.get_completions(
Document(text=text, cursor_position=cursor_positition), None)
def get_prompt(self, string):
sqlexecute = self.sqlexecute
host = self.login_path if self.login_path and self.login_path_as_host else sqlexecute.host
now = datetime.now()
string = string.replace('\\u', sqlexecute.user or '(none)')
string = string.replace('\\h', host or '(none)')
string = string.replace('\\d', sqlexecute.dbname or '(none)')
string = string.replace('\\t', sqlexecute.server_type()[0] or 'mycli')
string = string.replace('\\n', "\n")
string = string.replace('\\D', now.strftime('%a %b %d %H:%M:%S %Y'))
string = string.replace('\\m', now.strftime('%M'))
string = string.replace('\\P', now.strftime('%p'))
string = string.replace('\\R', now.strftime('%H'))
string = string.replace('\\r', now.strftime('%I'))
string = string.replace('\\s', now.strftime('%S'))
string = string.replace('\\p', str(sqlexecute.port))
string = string.replace('\\_', ' ')
return string
def run_query(self, query, new_line=True):
"""Runs *query*."""
results = self.sqlexecute.run(query)
for result in results:
title, cur, headers, status = result
self.formatter.query = query
output = self.format_output(title, cur, headers)
示例6: PythonCommandLineInterface
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import request_redraw [as 别名]
#.........这里部分代码省略.........
buffers.update(_extra_buffers or {})
self.cli = CommandLineInterface(
eventloop=eventloop,
style=style,
key_bindings_registry=self.key_bindings_manager.registry,
buffers=buffers,
paste_mode=Condition(lambda cli: self.settings.paste_mode),
layout=self._create_layout(),
on_abort=AbortAction.RETRY,
on_exit=AbortAction.RAISE_EXCEPTION)
def on_input_timeout():
"""
When there is no input activity,
in another thread, get the signature of the current code.
"""
if self.cli.focus_stack.current != 'default':
return
# Never run multiple get-signature threads.
if self.get_signatures_thread_running:
return
self.get_signatures_thread_running = True
buffer = self.cli.current_buffer
document = buffer.document
def run():
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
# Show signatures in help text.
if script:
try:
signatures = script.call_signatures()
except ValueError:
# e.g. in case of an invalid \\x escape.
signatures = []
except Exception:
# Sometimes we still get an exception (TypeError), because
# of probably bugs in jedi. We can silence them.
# See: https://github.com/davidhalter/jedi/issues/492
signatures = []
else:
signatures = []
self.get_signatures_thread_running = False
# Set signatures and redraw if the text didn't change in the
# meantime. Otherwise request new signatures.
if buffer.text == document.text:
self.settings.signatures = signatures
# Set docstring in docstring buffer.
if signatures:
string = signatures[0].docstring()
if not isinstance(string, six.text_type):
string = string.decode('utf-8')
self.cli.buffers['docstring'].reset(
initial_document=Document(string, cursor_position=0))
else:
self.cli.buffers['docstring'].reset()
self.cli.request_redraw()
else:
on_input_timeout()
self.cli.eventloop.run_in_executor(run)
def reset():
self.key_bindings_manager.reset()
self.settings.signatures = []
self.cli.onReset += reset
self.cli.onInputTimeout += on_input_timeout
def _create_layout(self):
"""
Generate new layout.
"""
return create_layout(
self.settings, self.key_bindings_manager, self.python_prompt_control,
lexer=self._lexer,
extra_buffer_processors=self._extra_buffer_processors,
extra_sidebars=self._extra_sidebars)
def _create_python_buffer(self):
def is_buffer_multiline():
return (self.settings.paste_mode or
document_is_multiline_python(b.document))
b = Buffer(
is_multiline=Condition(is_buffer_multiline),
complete_while_typing=Condition(lambda: self.settings.complete_while_typing),
enable_history_search=Always(),
tempfile_suffix='.py',
history=self.history,
completer=self.completer,
validator=self.validator)
return b
示例7: PythonCommandLineInterface
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import request_redraw [as 别名]
#.........这里部分代码省略.........
# Never run multiple get-signature threads.
if self.get_signatures_thread_running:
return
self.get_signatures_thread_running = True
buffer = self.cli.current_buffer
document = buffer.document
def run():
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
# Show signatures in help text.
if script:
try:
signatures = script.call_signatures()
except ValueError:
# e.g. in case of an invalid \\x escape.
signatures = []
except Exception:
# Sometimes we still get an exception (TypeError), because
# of probably bugs in jedi. We can silence them.
# See: https://github.com/davidhalter/jedi/issues/492
signatures = []
else:
signatures = []
self.get_signatures_thread_running = False
# Set signatures and redraw if the text didn't change in the
# meantime. Otherwise request new signatures.
if buffer.text == document.text:
buffer.signatures = signatures
# Set docstring in docstring buffer.
if signatures:
string = signatures[0].docstring()
if not isinstance(string, six.text_type):
string = string.decode('utf-8')
self.cli.buffers['docstring'].reset(
initial_document=Document(string, cursor_position=0))
else:
self.cli.buffers['docstring'].reset()
self.cli.request_redraw()
else:
on_input_timeout()
self.cli.eventloop.run_in_executor(run)
self.cli.onInputTimeout += on_input_timeout
self.cli.onReset += self.key_bindings_manager.reset
self.add_new_python_buffer()
def _update_layout(self):
"""
Generate new layout.
(To be done when we add/remove buffers.)
"""
self.cli.layout = create_layout(
self.cli.buffers, self.settings, self.key_bindings_manager, self.python_prompt_control,
lexer=self._lexer,
extra_buffer_processors=self._extra_buffer_processors,
extra_sidebars=self._extra_sidebars)
def add_new_python_buffer(self):
# Create a new buffer.
buffer = self._create_buffer()
self.settings.buffer_index += 1
name = 'python-%i' % self.settings.buffer_index
# Insert and update layout.
self.cli.add_buffer(name, buffer, focus=True)
self._update_layout()
def close_current_python_buffer(self):
name, _ = current_python_buffer(self.cli, self.settings)
if name:
python_buffers_left = len([b for b in self.cli.buffers if b.startswith('python-')])
if python_buffers_left > 1:
focus_next_buffer(self.cli, name_filter=lambda name: name.startswith('python-'))
del self.cli.buffers[name]
self._update_layout()
else:
self.cli.set_exit()
def _create_buffer(self):
def is_buffer_multiline(document):
return (self.settings.paste_mode or
self.settings.currently_multiline or
document_is_multiline_python(document))
return PythonBuffer(
is_multiline=is_buffer_multiline,
tempfile_suffix='.py',
history=self.history,
completer=self.completer,
validator=self.validator)