Przyjrzeniu sublime.py
widzimy, że metoda flush
faktycznie nic nie robi:
class _LogWriter:
def flush(self):
pass
def write(self, s):
sublime_api.log_message(s)
sys.stdout = _LogWriter()
sys.stderr = _LogWriter()
Jednak nie polecam korzystania z konsoli do wyniki użytkownika i tak. Zwykle korzystasz z paneli wyjściowych/widoków lub komunikatów o stanie.
Komunikaty o stanie są łatwiejsze w użyciu, ale mniej skuteczne. SergioFC zademonstrował to w his answer.
Pokazuje to, jak korzystać z panelu wyjściowego. Jest bardzo elastyczny, ale musisz napisać własne polecenie tekstowe, aby wstawić tekst. Jest to konieczne, ponieważ potrzebny jest obiekt do edycji, aby zmienić zawartość widoku.
import sublime
import sublime_plugin
class MyInsertProgressBarCommand(sublime_plugin.TextCommand):
def run(self, edit, value):
view = self.view
width, _ = view.viewport_extent()
em_width = view.em_width()
# the number of columns are the width divided by the width of a char
# subtract two to add a little border
columns = int(width/em_width) - 2
# subtract two, because we surround it with [ and ]
bar_length = columns - 2
# calculate the size of the filled and the remaining part
filled_length = int(bar_length * value/100)
remaining_length = bar_length - filled_length
# assemble the string for the progress bar
text = "[{0}{1}]\n".format("=" * filled_length, "." * remaining_length)
# add the text for the percentages
if value >= 100:
percentage_text = "finished!"
else:
percentage_text = "{:3.2f} %".format(value)
text += " " * (columns - len(percentage_text)) + percentage_text
# replace the content of the view
view.replace(edit, sublime.Region(0, view.size()), text)
# reset sels
view.sel().clear()
view.sel().add(sublime.Region(0, 0))
class ProgressBarCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.create_output_panel("progess_bar")
self.window.run_command("show_panel", {"panel": "output.progess_bar"})
def test_progress_bar():
import random
test_progress_bar.value += 2 * random.random()
if test_progress_bar.value >= 100:
self.finish_progress()
return
self.show_progress(test_progress_bar.value)
sublime.set_timeout(test_progress_bar, 100)
test_progress_bar.value = 0
sublime.set_timeout_async(test_progress_bar, 1)
def show_progress(self, progess):
view = self.window.find_output_panel("progess_bar")
view.run_command("my_insert_progress_bar", {"value": progess})
def finish_progress(self):
self.show_progress(100)
sublime.set_timeout(self._destroy, 5000)
def _destroy(self):
self.window.destroy_output_panel("progess_bar")
Wyjście:
Nie jestem do końca pewien, o co pytasz - czy miałeś na myśli to, że ze względu na dużą liczbę linii wynik wygląda naprawdę "spamowo", powodując nieprzyjemne wyniki? – Jerrybibo
Tak, miałem na myśli. Edytuję pytanie w celu wyjaśnienia. –