简体   繁体   中英

unexpected indent outputs of print function with multithreads in python

I have been trying to write a keyboard listener without installing any packages. What I wanted was to create a non-blocking way of reading only one character of user input. So I created another thread besides the main one. Here is my code:

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);

And the printed strings are a bit weird:

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

See those indents? I never expected to have that. And I have been trying a whole afternoon to solve it but failed. Does anybody know how to solve this? I will be so grateful. (btw I'm using a macbook pro.)

Putting STDIN in raw mode put STDOUT in raw mode as well, so the normal \\n is not expanded to a CRLF. You will need to print a \\r at the end of your string in order to return the cursor to the first column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM