How to dynamically update terminal output on multiple lines in python3?

余生长醉 提交于 2021-01-29 10:02:23

问题


I am trying to write a program that will emulated a 20x4 character LCD screen by printing data dynamically to a terminal. Currently I am just trying to get the output to the terminal to work but I can't figure out how to print on multiple lines concurrently without using new line characters.

import time

i = 0
for i in range(0, 9):
    print(str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i), end='\r')
    print(str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i), end='\r')
    print(str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i) +
          str(i) + str(i) + str(i) + str(i) + str(i), end='\r')

    time.sleep(1)

Currently this code prints one line of 20 characters that updates correctly but I need the additional two lines below it. The expected output I would like is 4 lines of 20 characters each that updates dynamically. Eventually, each line would just be one string for the 20 characters.


回答1:


You should be able to achieve this using f string format and docstring.

Refer to the Official Documentation for F Strings(formatted string literals) here

The code should look like this.

import time

i = 0
for i in range(0, 9):
    print(f"""
          {str(i)} {str(i)} {str(i)} {str(i)} {str(i)} 
          {str(i)} {str(i)} {str(i)} {str(i)} {str(i)}
          {str(i)} {str(i)} {str(i)} {str(i)} {str(i)} 
          {str(i)} {str(i)} {str(i)} {str(i)} {str(i)} """)

    time.sleep(1)

Please let me know if this help if it's not what you are looking for let me know so I can help you figure something more suitable for your needs.




回答2:


Adjusting Rodrez's answer slightly:

import time

i = 0

goback = "\033[F" * 5  # 👈 this "climbs you back up 5 lines" at the next
                       # iteration, output at same spot, like `top`


for i in range(0, 9):
    print(f"""{goback}
          {i} {i} {i} {i} {i} 
          {i} {i} {i} {i} {i}
          {i} {i} {i} {i} {i} 
          {i} {i} {i} {i} {i} """)

    time.sleep(1)


see https://stackoverflow.com/a/11474509 for where I got the weird characters from.



来源:https://stackoverflow.com/questions/60742955/how-to-dynamically-update-terminal-output-on-multiple-lines-in-python3

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