Skip to content
Advertisement

Python cmd module – Resume prompt after asynchronous event

I am maintaining an operator terminal based on cmd. The customer asked for an alerting behavior. e.g. a message shown onscreen when some asynchronous event occurs. I made a thread that periodically checks for alerts, and when it finds some, it just prints them to stdout.

This seems to work OK, but it doesn’t seem very elegant, and it has a problem:

Because cmd doesn’t know an alert happened, the message is followed onscreen by blank. The command prompt is not reprinted, and any user input is left pending.

Is there a better way to do asynchronous alerts during Python cmd? With the method as-is, can I interrupt cmd and get it to redraw its prompt?

I tried from my thread to poke a newline in stdin using StringIO, but this is not ideal, and I haven’t gotten it work right.

Example code:

JavaScript

Advertisement

Answer

I ended up overriding Cmd.cmdloop with my own version, replacing the readlines() with my own readlines that use non-blocking terminal IO.

Non-Blocking terminal IO info here: Non-Blocking terminal IO

Unfortunately, this opens another can trouble in that it is messy and breaks auto-completion and command history. Fortunately, the customer was OK with having to push Enter to redo the prompt, so I don’t need to worry about it anymore.

Incomplete example code showing the non-blocking terminal input approach:

JavaScript
Advertisement