Python 诅咒从 stdin 读取单个字符会影响 print 语句的输出

发布于 2024-12-04 10:54:47 字数 469 浏览 0 评论 0原文

我正在尝试从标准输入中非阻塞读取单个字符。我已经找到了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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你在看孤独的风景 2024-12-11 10:54:48
#!/usr/bin/python -tt
#youres to use
import curses
from time import sleep

def callback(screen):
  screen.nodelay(1)
  return screen.getkey()

def getkey():
  try:
    key = curses.wrapper(callback)
  except:
    key = None
  return key

#tryer
while 1:
  sleep(1)
  k= getkey()
  if k != None:
    print "goo", k
  else:
    print "foo"
#!/usr/bin/python -tt
#youres to use
import curses
from time import sleep

def callback(screen):
  screen.nodelay(1)
  return screen.getkey()

def getkey():
  try:
    key = curses.wrapper(callback)
  except:
    key = None
  return key

#tryer
while 1:
  sleep(1)
  k= getkey()
  if k != None:
    print "goo", k
  else:
    print "foo"
你好,陌生人 2024-12-11 10:54:47

看来使用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.

離殇 2024-12-11 10:54:47

在启动正确的curses窗口的情况下,只有screen.addch('\n')对我有用(在这种情况下,回车符和换行符都是打印);即使指定了 \r\n,我也无法让 print (或者更确切地说,sys.stdout.write)“表现”。

In the case proper curses window is started, only screen.addch('\n') worked for me (in which case, both the carriage return and the line feed are printed); I couldn't get print (or rather, sys.stdout.write) to "behave", even with specifying \r\n.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文