Python 诅咒从 stdin 读取单个字符会影响 print 语句的输出
我正在尝试从标准输入中非阻塞读取单个字符。我已经找到了curses库的解决方案,但是当我尝试将输出写回标准输出时,我做错了一些事情。
import curses
from time import sleep
def callback(screen):
screen.nodelay(1)
return screen.getkey()
while 1:
try:
key = curses.wrapper(callback)
print "Got keypress: ", key
except:
sleep(3)
print "No Keypress"
print "Program\nOutput"
# Prints
No Keypress
Program
Output
除了缩进输出之外,一切都完美无缺。有什么办法可以解决这个问题吗?
I'm trying to do a non-blocking read of a single character from stdin. I have found a solution with the curses library, but I'm doing something wrong when trying to write output back to stdout.
import curses
from time import sleep
def callback(screen):
screen.nodelay(1)
return screen.getkey()
while 1:
try:
key = curses.wrapper(callback)
print "Got keypress: ", key
except:
sleep(3)
print "No Keypress"
print "Program\nOutput"
# Prints
No Keypress
Program
Output
Everything works flawlessly with the exception of the indented output. Is there any way to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看来使用curses,'\n'只是一个换页符。您可能还需要输出回车符,或者显式使用curses 来重新定位光标。
It would appear that using curses, '\n' is just a form feed. You presumably need to output a carriage return as well, or else explicitly use curses to reposiition the cursor.
在启动正确的curses窗口的情况下,只有screen.addch('\n')对我有用(在这种情况下,回车符和换行符都是打印);即使指定了
\r\n
,我也无法让print
(或者更确切地说,sys.stdout.write
)“表现”。In the case proper
curses
window is started, onlyscreen.addch('\n')
worked for me (in which case, both the carriage return and the line feed are printed); I couldn't getprint
(or rather,sys.stdout.write
) to "behave", even with specifying\r\n
.