Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python \r即使在进行另一次打印后,也要在同一行上保持打印时间_Python_Python 3.x_Printing_Newline - Fatal编程技术网

Python \r即使在进行另一次打印后,也要在同一行上保持打印时间

Python \r即使在进行另一次打印后,也要在同一行上保持打印时间,python,python-3.x,printing,newline,Python,Python 3.x,Printing,Newline,我有一个线程,它每1秒计算一次时间,以获得总运行时间。这是伟大的作品,但我需要使它保持在同一行,即使在打印另一行。目前它正在这样做: [~] 00:00:02 ok #this is a test print to see if it stays on the same line and of course it dosen't. [~] 00:00:08 这是我的密码。我一直在读关于\r\n和\r\n的文章,并且\r\n做了部分工作,但我仍然需要它始终保持在同一条线上。我甚至不确定这是否可行

我有一个线程,它每1秒计算一次时间,以获得总运行时间。这是伟大的作品,但我需要使它保持在同一行,即使在打印另一行。目前它正在这样做:

[~] 00:00:02
ok #this is a test print to see if it stays on the same line and of course it dosen't.
[~] 00:00:08

这是我的密码。我一直在读关于\r\n和\r\n的文章,并且\r\n做了部分工作,但我仍然需要它始终保持在同一条线上。我甚至不确定这是否可行,尽管我在其他语言中看到过,所以我认为是这样。

您可以使用
\r
重写底线

如果要在“时间戳”上方打印其他内容(如“确定”):

  • 首先用时间戳擦除底线(如果下一行不够长,可能需要用空格覆盖,然后再次使用
    \r
    ),然后
  • 打印另一件东西(“确定”),然后
  • 将时间戳再次写在它下面的新行上
比如说,

>>> from datetime import datetime
>>> import time
>>> for c in 'abcdefg':
...   print(datetime.now(), end='\r')  # timestamp
...   time.sleep(1)
...   print(' '*80, end='\r')  # overwrite timestamp line with spaces
...   print(c)  # print something else "above" the next timestamp
...
a
b
c
d
e
f
g
>>>
最终结果没有时间戳,但在循环时可以看到它。试试看

如果开始时没有滚动到底部,则时间戳行会“移动”,但一旦打印足够的行以填充终端,则底线将保留在底部。您还可以使用它来显示进度条和微调器等


还请注意,您可以使用退格字符来备份一个字符,而不是使用回车来备份到行首。

这需要“curses”或类似的库。这是否回答了您的问题?你能提供一段代码。。。ngl这太令人困惑了。这不是我需要的,它似乎像你说的那样,但我需要它来保持时间戳在顶部,而不是字母,不知道为什么,但在重新安排语句后,我仍然无法保持时间戳在顶部
\r
仅在最后一行有效,抱歉。你的问题只是说它必须在同一条线上。如果你想在控制台中编辑任意位置,你确实需要一些类似于curses的东西。有一些特殊的“转义序列”可以在终端上移动光标,类似于colorama产生的颜色变化序列。但它的工作方式取决于终端类型,不像大多数终端上使用的
\r
技巧。要正确地执行它,您几乎必须重新实现诅咒,因此您不妨直接使用它。
>>> from datetime import datetime
>>> import time
>>> for c in 'abcdefg':
...   print(datetime.now(), end='\r')  # timestamp
...   time.sleep(1)
...   print(' '*80, end='\r')  # overwrite timestamp line with spaces
...   print(c)  # print something else "above" the next timestamp
...
a
b
c
d
e
f
g
>>>