gpt4 book ai didi

python - python中多线程打印函数的意外缩进输出

转载 作者:行者123 更新时间:2023-12-01 05:01:30 27 4
gpt4 key购买 nike

我一直在尝试编写一个键盘监听器而不安装任何软件包。我想要的是创建一种仅读取用户输入的一个字符的非阻塞方式。所以我除了主线程之外还创建了另一个线程。这是我的代码:

import sys, os 
import thread
import time

try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

char = None;

def key_listener():
global char;
while True:
char = getch()
# escape key to exit
if ord(char) == 27:
break
#print char #comment this line for test

thread.start_new_thread(key_listener, ())

while True:
print("Whatever")
time.sleep(1);

打印的字符串有点奇怪:

Yinans-MacBook-Pro:anaconda game Yinan$ python inputtest.py 
Whatever
Whatever
Whatever
Whatever
Whatever
Whatever

看到那些缩进了吗?我从没想过会有这样的事。我花了一下午的时间试图解决这个问题但失败了。有人知道如何解决这个问题吗?我将非常感激。 (顺便说一句,我使用的是 MacBook Pro。)

最佳答案

将 STDIN 置于原始模式也会将 STDOUT 置于原始模式,因此正常的 \n 不会扩展为 CRLF。您需要在字符串末尾打印 \r 以便将光标返回到第一列。

关于python - python中多线程打印函数的意外缩进输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26029436/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com