Python命令行打印在同一行

时间:2016-05-31 02:36:05

标签: python shell terminal

在同一条线上有很多与打印有关的问题,但在终端内的同一条线上打印多条线也没有任何问题。

例如:

n_class = 1

我希望这些流程的进度在同一行上更新,而不是一遍又一遍地打印。我已经查看过使用返回托架字符ogeno@OH-ogeno-MBP:~|⇒ python my_script.py Process 1: 5% Process 2: 14% Process 3: 55% \r的其他问题,但它似乎没有将插入符号更改为一行,直到当前结束线。

编辑:我的问题不同,因为它与在终端的同一行上打印MULTIPLE行有关。如果它只是一行就很容易。

3 个答案:

答案 0 :(得分:1)

一种方法是使用ANSI escape-code "\033[F"转到上一行的开头。以下在我的所有终端都运行良好,只需从当前终端位置写下两行:

import time
import sys

progress_1 = 'Process 1: {}%'
progress_2 = 'Process 2: {}%'
print
print

for i in range(100):
    sys.stdout.write('\033[F')
    sys.stdout.write('\033[F')
    print(progress_1.format(i))
    print(progress_2.format(i))
    time.sleep(0.02)

答案 1 :(得分:0)

你可以使用

for python 2.7,

print 2%, 3% # Using comma will print it in same line

for python 3.x

print('2%', end=" ")

或者您可以使用sys.stdout.write来使用sys.stdout.flush() 请检查下面的代码,我已经创建了一个演示进度条。

"""ProgressBar Module."""

import sys
import time


class ProgressBar(object):
    """Main class for the ProgressBa."""

    DEFAULT_BAR_LENGTH = float(30)

    def __init__(self, start=0, step=1):
        """Init for the class."""
        self.end = ProgressBar.DEFAULT_BAR_LENGTH
        self.start = start
        self.step = step
        self.total = self.end - self.start
        self.counts = self.total / self.step
        self._barLength = ProgressBar.DEFAULT_BAR_LENGTH

        self.set_level(self.start)
        self._plotted = False

    def set_level_old(self, level, initial=False):
        """Setting Level."""
        self._level = level
        if level < self.start:
            self._level = self.start
        if level > self.end:
            self._level = self.end

        self._ratio = float(
            self._level - self.start) / float(self.end - self.start)
        self._levelChars = int(self._ratio * self._barLength)

    def set_level(self, level, initial=False):
        """Setting Level."""
        self._level = level
        if level < self.start:
            self._level = self.start
        if level > self.end:
            self._level = self.end

        self._ratio = float(self._level) / float(self._barLength)
        self._levelChars = int(self._ratio * self._barLength) * self.step

    def plot_progress(self):
        """Plotting the bar."""
        sys.stdout.write("\r  %3i%%  |%s%s|" % (
            int(self._ratio * self.step * 100.0),
            u'\u2588' * int(self._levelChars),
            ' ' * int(self._barLength - self._levelChars),
        ))
        sys.stdout.flush()
        self._plotted = True

    def set_and_plot(self, level):
        """Call the plot."""
        old_chars = self._levelChars
        self.set_level(level)
        if (not self._plotted) or (old_chars != self._levelChars):
            self.plot_progress()

    def __del__(self):
        """Del for the class."""
        sys.stdout.write("\n")

if __name__ == "__main__":

    pb = ProgressBar(0, 1)

    curProgress = 0
    pb.plot_progress()
    while curProgress <= pb.counts:
        pb.set_and_plot(curProgress)
        curProgress += 1
        time.sleep(0.1)

    del pb

答案 2 :(得分:0)

使用退格键可以轻松完成。以下是将在同一行打印百分比的示例代码。

import time
print "Work in progress(0%%)", # Python 2 print without newline
for work_done in range(10):
    print "\b\b\b\b\b%2d%%)" % work_done, # Backspace then overwrite
    time.sleep(1)