从功能返回后如何使控制台闪烁?

How to make console flash after returning from function?

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

我的第一个想法是:

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 调用。

这行得通,但是这样就可以在闪烁停止时显示输入提示,即在用户激活命令后 window。

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

想通了!由于每当调用 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} """)