【问题标题】:Is It possible to write in the same line and don't write in several row? [duplicate]是否可以写在同一行而不写多行? [复制]
【发布时间】:2019-10-30 09:07:54
【问题描述】:

我会用这个简单的 python 脚本打印 CPU 使用情况。我会写出结果,擦除该行并在同一行重新写入,就像 windows shell 对某些命令所做的那样。有可能吗?

import psutil                                     #import tsutil
import time

def printit():
    while(1):
        print(psutil.cpu_percent())
        time.sleep(3)
printit()

此打印行每行。我希望结果总是在同一行发生变化

【问题讨论】:

  • 使用print('text content', end='')

标签: python python-3.x psutil


【解决方案1】:

是的,使用print(psutil.cpu_percent(), end=' ')

您还需要刷新标准输出,因为除非您打印换行符,否则内容实际上不会打印在屏幕上。

试试这个:

import psutil
import time
import sys

def printit():
    while(1):
        print(psutil.cpu_percent(), end=' ')
        sys.stdout.flush()
        time.sleep(3)
printit()

【讨论】:

    【解决方案2】:

    在打印功能上使用回车

    import psutil
    import time
    import sys
    
    def printit():
        while(1):
            print('{:06.2f}'.format(psutil.cpu_percent()), end='\r')
            time.sleep(3)
    printit()
    

    更新:如果字符串大小不同,使用 \r 会中断,格式可以解决这个问题

    【讨论】:

      猜你喜欢
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      相关资源
      最近更新 更多