Python: 没有输入被打散的打印行

Python: Print Lines without Input Being broken up

我正在尝试为小型 AngularJS 应用制作一个简单的多线程命令提示符,我是 运行。

在这个提示中,我想输入一个命令而不被输出打断,如下所示:

Output
More output HTTP 1.0
HTTP Request from 127.0.0.1 for /img/foo.png - 200
> Humble command I'm ty-OH NO BUT MORE OUTPUT
SUCH ANNOYING OUTPUT FOR FAVICON.ICO - 404
-ping.. Dang it.

相反,我想要这样:

Output
More output HTTP 1.0
HTTP Request from 127.0.0.1 for /img/foo.png - 200
OH NO BUT MORE OUTput and it's not breaking up what
you're typing... :/ - favicon.ico 404 btw...
> Humble command I'm typing that's not broken up

我不确定在命令提示符下是否可行,如果需要,我可能只导入 pygame 或者看一下 pyglet,但我相信命令提示符会更好为了我的目的。

希望我已为您解释清楚,但如果您需要更多信息,请在下方提问!

使用Python3.x

Gist

这是它的样子

编辑: 我添加了 cmd.Cmd 作为我的命令提示符并按照 J. F. Sebastian 告诉我的去做,但是它的行为..很奇怪..

听起来您想 运行 python 脚本作为后台进程:

>python yourScript.py &
>now it won't interrupt you but you'll have to pipe output to a file if you want to read it

& 就是这样做的。

如果你想在 Python 中 运行 后台不输出的脚本 ,我会考虑使用 threading

为避免其他线程的输出中断您的输入,请组织您的脚本以仅在主线程中执行标准 I/O,例如,将 sys.stdoutsys.stderr 替换为类似文件的对象当您完成输入时,该队列写入并使用队列:

import sys
from queue import Queue, Empty

class QueuedFile:
   def __init__(self, queue):
       self.queue = queue
   def write(self, text):
       self.queue.put(text)
   def flush(self):
       pass # noop

q = Queue()
sys.stdout = sys.stderr = QueuedFile(q)

# print from multiple threads while accepting input...

# print queued output
while True:
    try:
        sys.__stdout__.write(q.get(block=False))
    except Empty:
        break # no more output