So I have a script that will continuously read from a sensor, print a carriage return and then the sensor value. It does this until raw_input()
finishes blocking (enter pressed).
However, when I run it, instead of an increasing number, I see blank space. When I press enter, one number is printed and then the program exits. If \\r
is replaced by \\n
, the program runs as it should, printing out the "sensor" value ( i = i + 1
is a placeholder for the reading of the sensor), but instead of reusing the same line it prints it on a new line. Why does it not work with \\r
? Here is the full code:
from threading import Thread
from time import sleep
import sys
running = True
def loop():
i = 0
while running:
sys.stdout.write("\r" + str(i))
i = i+1
sleep(0.1)
thread = Thread(target=loop)
thread.start()
raw_input()
running = False
thread.join()
The difference is that writing out the newline flushes the channel, while writing out a carriage return (or most other character) doesn't. You can get the same behaviour by adding an explicit flush after the write():
sys.stdout.flush()
As to why the lack of a flush causes the raw_input() to never return, I believe this is due to the buffering present on stdout; however, I've not been able to find more details.
I was trying things and tried flushing the output with sys.stdout.flush()
and it worked. Thank you all for your help.
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.