python Force git hook server side output on same line in realtime

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-07 03:49:06

问题


git hooks server side output only transmits on a newline. I want to configure a custom task and print real-time output on the same line. How can I achieve that? I tried sys.stdout.flush but it transmits everything once complete. It does work in real-time if I add a newline. I want something like

Step A)Started......Completed

with each '.' appended after a given time.

My current code looks like the following and it outputs only when the method is completed.

import sys, time, os


def print_realtime():
    sys.stdout.write('Started.')
    sys.stdout.flush()
    time.sleep(1)
    for i in range(1, 15):
        sys.stdout.write('.')
        sys.stdout.flush()
        time.sleep(0.5)

if __name__ == "__main__":
    print_realtime()

However, it works in realtime if I append '\n' like:

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

回答1:


The problem comes down to the fact that Git itself does not print accumulated remote: text until the remote sends either a newline or carriage return.

Hence, if we change your inner loop to read:

for i in range(1, 15):
    sys.stdout.write('.' * i + '\r')
    sys.stdout.flush()
    time.sleep(0.5)

you will see the effect you desire.

Note that the \r moves the print position back to just after the word remote:, so we must repeat what we have printed so far (hence the need to print first one ., then two .s, then three, and so on).



来源:https://stackoverflow.com/questions/44128813/python-force-git-hook-server-side-output-on-same-line-in-realtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!