【问题标题】:How to make console flash after returning from function?从功能返回后如何使控制台闪烁?
【发布时间】:2021-11-29 07:29:01
【问题描述】:

我正在尝试编写一个 CUI 应用程序,其中窗口应该在 从自定义功能返回后闪烁。这将使闪烁发生在显示输入提示之后,而不是事先。

我的第一个想法是:

from ctypes import windll

def custom_formatted_input():
    while get_foreground_window_title() != "cmd.exe":
        windll.user32.FlashWindow(windll.kernel32.GetConsoleWindow(), True)
        time.sleep(0.5)
    return input(f"""{time.strftime("%Y-%m-%d %H:%M:%S")}{"".ljust(4)}[INPUT]{"".ljust(6)}{message} """)

其中get_foreground_window_title 是通过 ctypes 调用的 Windows API。

这是可行的,但是这样可以在闪烁停止时显示输入提示,即在用户激活 cmd 窗口之后。

我怎样才能让它在输入函数返回后发生这种闪烁?我相信这将需要一个装饰器,但是我无法自己找出解决方案。谢谢!

【问题讨论】:

  • input的调用结果赋值给一个变量,然后触发flash,最后返回保存的结果
  • @IainShelvington,如果我将输入的值保存到变量中,则会停止执行并等待输入完成。这样在用户输入提示完成后会闪烁。
  • 您希望在显示输入提示时开始闪烁?

标签: python python-decorators


【解决方案1】:

想通了!由于每当调用input() 时执行总是会停止,因此闪烁需要在执行停止时发生,即在另一个线程上。

代码:

def flash_window():
    while "cmd.exe" not in get_foreground_window_title():
        windll.user32.FlashWindow(windll.kernel32.GetConsoleWindow(), True)
        time.sleep(0.5)


def input_log(message):
        t1 = threading.Thread(target=flash_window)
        t1.start()
        return input(f"""{time.strftime("%Y-%m-%d %H:%M:%S")}{"".ljust(4)}[INPUT]{"".ljust(6)}{message} """)

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2013-04-14
    • 2021-06-07
    • 2022-01-01
    • 2016-04-16
    • 1970-01-01
    相关资源
    最近更新 更多