gpt4 book ai didi

python - 在新 View (未保存的缓冲区)中打印文本,而不是在控制台中

转载 作者:行者123 更新时间:2023-12-01 03:03:50 26 4
gpt4 key购买 nike

1.简要

我没有找到,如何在新 View 中获得输出,而不是在 Sublime Text 控制台中。

2. 预期行为

例如,我有倒数计时器:

import time

seconds = 10

while seconds >= 0:
time.sleep(1)
if seconds == 5:
print("5 seconds")
elif seconds == 0:
print("Time over!")
time.sleep(5)
else:
print(seconds)
seconds -= 1

Ctrl+Shift+P(Mac 为⌘⇧p)→ SublimeREPL: Python RUN current file → 我得到预期的行为:

Countdown timer

3.实际行为

Sublime Text 插件中的相同倒数计时器:

import time

import sublime_plugin

seconds = 10


class LovernaStandardCommand(sublime_plugin.TextCommand):

def run(self, edit):
current_id = self.view.id()
if current_id:
global seconds
while seconds >= 0:
time.sleep(1)
if seconds == 5:
print("5 seconds")
elif seconds == 0:
print("Time over!")
time.sleep(5)
else:
print(seconds)
seconds -= 1

我运行命令 loverna_standard → 我在 Sublime Text 控制台中看到输出,而不是在新 View 中。

4.没有帮助
  • python write() method适用于文件,不适用于未保存的缓冲区。
  • 我在 Sublime Text 3 API documentation 中找到, 如何打开新 View — sublime.active_window().new_file() - 但我不知道如何在此 View 中打印文本。
  • 最佳答案

    您可以使用 append 将文本附加到 Sublime Text View 。命令。
    例如,如果您希望 View 在添加新文本时自动滚动到底部:

    view.run_command('append', { 'characters': str(seconds) + '\n', 'scroll_to_end': True })

    但是,最好每秒设置一次回调,而不是休眠,否则 ST 将在命令运行时无响应。
    import sublime
    import sublime_plugin

    class LovernaStandardCommand(sublime_plugin.TextCommand):

    def run(self, edit, seconds=10):
    self.print_seconds(sublime.active_window().new_file(), seconds)

    def print_seconds(self, view, seconds):
    text = ''
    if seconds > 0:
    text = str(seconds)
    if seconds == 5:
    text += ' seconds'
    sublime.set_timeout_async(lambda: self.print_seconds(view, seconds - 1), 1000)
    else:
    text = 'Time over!'
    view.run_command('append', { 'characters': text + '\n', 'scroll_to_end': True })

    关于python - 在新 View (未保存的缓冲区)中打印文本,而不是在控制台中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43582232/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com