小编Cra*_*llo的帖子

Python cmd 模块 - 异步事件后恢复提示

我正在维护一个基于 cmd 的操作员终端。客户要求报警行为。例如,当某个异步事件发生时,屏幕上会显示一条消息。我创建了一个线程来定期检查警报,当它找到一些时,它只是将它们打印到标准输出。

这似乎工作正常,但它似乎不是很优雅,并且有一个问题:

由于 cmd 不知道发生了警报,因此屏幕上的消息后面跟着空白。不会重新打印命令提示符,并且任何用户输入都处于未决状态。

有没有更好的方法在 Python cmd 期间执行异步警报?使用原样的方法,我可以中断 cmd 并让它重绘其提示吗?

我尝试从我的线程中使用 StringIO 在 stdin 中插入一个换行符,但这并不理想,而且我还没有让它正常工作。

示例代码:

import cmd, sys
import threading, time
import io
import sys

class MyShell(cmd.Cmd):
    intro = '*** Terminal ***\nType help or ? to list commands.\n'
    prompt = '> '
    file = None

    def alert(self):
        time.sleep(5)
        print ('\n\n*** ALERT!\n')
        sys.stdin = io.StringIO("\n")

    def do_bye(self, arg):
        'Stop recording, close the terminal, and exit:  BYE'
        print('Exiting.')
        sys.exit(0)
        return True

    def do_async(self, arg):
        'Set a five second …
Run Code Online (Sandbox Code Playgroud)

python alert asynchronous cmd

5
推荐指数
1
解决办法
833
查看次数

标签 统计

alert ×1

asynchronous ×1

cmd ×1

python ×1