program tip

Python에서 콘솔 출력 교체

radiobox 2020. 9. 21. 07:34
반응형

Python에서 콘솔 출력 교체


특정 C / C ++ 프로그램에서와 같이 Python에서 멋진 콘솔 카운터 중 하나를 어떻게 만들 수 있는지 궁금합니다.

나는 일을하는 루프가 있고 현재 출력은 다음과 같습니다.

Doing thing 0
Doing thing 1
Doing thing 2
...

더 깔끔한 것은 마지막 라인 업데이트 만하는 것입니다.

X things done.

여러 콘솔 프로그램에서 이것을 보았고 파이썬에서 이것을 어떻게할지 궁금합니다.


쉬운 해결책은 "\r"줄 바꿈을 추가하지 않고 문자열 앞에 쓰는 것입니다 . 문자열이 짧아지지 않으면 충분합니다 ...

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

진행률 표시 줄이 약간 더 정교합니다. 이것은 제가 사용하는 것입니다.

def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

당신은 호출 startProgress작업의 설명을 통과 한 후 progress(x)위치를 x마지막으로 백분율입니다endProgress()


더 우아한 솔루션은 다음과 같습니다.

def progressBar(value, endvalue, bar_length=20):

        percent = float(value) / endvalue
        arrow = '-' * int(round(percent * bar_length)-1) + '>'
        spaces = ' ' * (bar_length - len(arrow))

        sys.stdout.write("\rPercent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))))
        sys.stdout.flush()

값과 끝값으로이 함수를 호출하면 결과는

Percent: [------------->      ] 69%

The other answer may be better, but here's what I was doing. First, I made a function called progress which prints off the backspace character:

def progress(x):
    out = '%s things done' % x  # The output
    bs = '\b' * 1000            # The backspace
    print bs,
    print out,

Then I called it in a loop in my main function like so:

def main():
    for x in range(20):
        progress(x)
    return

This will of course erase the entire line, but you can mess with it to do exactly what you want. I ended up make a progress bar using this method.


For anyone who stumbles upon this years later (like I did), I tweaked 6502's methods a little bit to allow the progress bar to decrease as well as increase. Useful in slightly more cases. Thanks 6502 for a great tool!

Basically, the only difference is that the whole line of #s and -s is written each time progress(x) is called, and the cursor is always returned to the start of the bar.

def startprogress(title):
    """Creates a progress bar 40 chars long on the console
    and moves cursor back to beginning with BS character"""
    global progress_x
    sys.stdout.write(title + ": [" + "-" * 40 + "]" + chr(8) * 41)
    sys.stdout.flush()
    progress_x = 0


def progress(x):
    """Sets progress bar to a certain percentage x.
    Progress is given as whole percentage, i.e. 50% done
    is given by x = 50"""
    global progress_x
    x = int(x * 40 // 100)                      
    sys.stdout.write("#" * x + "-" * (40 - x) + "]" + chr(8) * 41)
    sys.stdout.flush()
    progress_x = x


def endprogress():
    """End of progress bar;
    Write full bar, then move to next line"""
    sys.stdout.write("#" * 40 + "]\n")
    sys.stdout.flush()

If I understood well (not sure) you want to print using <CR> and not <LR>?

If so this is possible, as long the console terminal allows this (it will break when output si redirected to a file).

from __future__ import print_function
print("count x\r", file=sys.stdout, end=" ")

It can be done without using the sys library if we look at the print() function

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here is my code:

def update(n):
    for i in range(n):
        print("i:",i,sep='',end="\r",flush=True)
        #time.sleep(1)

In python 3 you can do this to print on the same line:

print('', end='\r')

Especially useful to keep track of the latest update and progress.

I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.


Added a little bit more functionality to the example of Aravind Voggu:

def progressBar(name, value, endvalue, bar_length = 50, width = 20):

        percent = float(value) / endvalue

        arrow = '-' * int(round(percent*bar_length) - 1) + '>'

        spaces = ' ' * (bar_length - len(arrow))

        sys.stdout.write("\r{0: <{1}} : [{2}]{3}%".format(\
                         name, width, arrow + spaces, int(round(percent*100))))

        sys.stdout.flush()

        if value == endvalue:        

             sys.stdout.write('\n\n')

Now you are able to generate multiple progressbars without replacing the once before.
I´ve also added name as a value with a fixed width.

For two loops and two times the use of progressBar() the result will look like:


enter image description here

참고URL : https://stackoverflow.com/questions/6169217/replace-console-output-in-python

반응형