简体   繁体   English

sys.stdout.write和\\ r回车不起作用

[英]sys.stdout.write and \r carriage return not working

I was following a little tutorial and after much research, I can't figure out why the given code doesn't print on the same line. 我遵循了一些教程,并且经过大量研究,所以我无法弄清楚为什么给定的代码没有打印在同一行上。 I copied it directly, so it should work. 我直接复制了它,因此它应该可以工作。

import time
import sys
sys.stdout.write('29 seconds remaining')
time.sleep(1)
sys.stdout.write('\r28 seconds remaining')

Output is: 输出为:

29 seconds remaining
28 seconds remaining

Final output should be: 最终输出应为:

28 seconds remaining

I put the "\\r" at the end of the line, not at the front. 我将“ \\ r”放在行的末尾,而不是在最前面。 Like this: 像这样:

 sys.stdout.write("%s[%s%s] %2i/%i\r" % (variables go here))
 sys.stdout.flush()

After trying out solutions that seemed to work for others with the same setup like me, I had to find out the hard way that carriage return sequences are parsed by the shell that outputs the printed string (please correct me here if not precise enough). 在尝试了对像我这样具有相同设置的其他人似乎可行的解决方案之后,我不得不找出一种困难的方式,即通过输出打印字符串的外壳来解析回车序列 (如果不够精确,请在此处进行纠正)。 I started getting closer to the solution when i realised that the windows command prompt (C:\\Windows\\System32\\cmd.exe) actually interpreted the carriage return as expected, but the PyScripter IDE did not. 当我意识到Windows命令提示符(C:\\ Windows \\ System32 \\ cmd.exe)实际上按预期解释了回车符时,我开始更接近该解决方案,但是PyScripter IDE却没有。 Then I realised that the PyScripter developers new about this, but did not want to spend the effort of mimicking the cmd.exe behaviour. 然后我意识到PyScripter开发人员对此有了新的认识,但不想花费很多精力来模仿cmd.exe行为。

Hope this puts fellow developers in the right direction and will save some time. 希望这可以使其他开发人员朝正确的方向发展,并可以节省一些时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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