简体   繁体   中英

Terminal dynamic print urls in python

I have a file containing urls (google.com, microsoft.com, etc). I want to print one url, then clear previous line from it. again write another url above. Code sample is below:

import sys
with open('url.txt') as u:
    for line in u:
          line=line.strip()
          print(line, end="\r")
          #also tried
          sys.stdout.write("\r{0}".format(line))
          sys.stdout.flush()

above code doesn't delete all previous chars. Example: "google.com" after "microsoft.com" will print as "google.com.com". Anybody can tell me how to delete previous line completely?

Try this:

import sys
import time
with open('url.txt') as u:
  lastline = ""
  for count, line in enumerate(u.readlines()):
    if count != 0:  # do not delay on first item outputted
      time.sleep(4)  # 4 sec delay so user can read before next text appears
    line = str(line).strip("\n")
    print(' ' * (len(lastline) + 1), end='\r')  # clear last line
    print(line, end='\r')
    lastline = line

Tested on windows 10

Though, the cursor will be blinking at the start. To fix this, you can install the cursor module by pip install cursor and then use this slightly modified code:

import sys
import time
import cursor
with open('url.txt') as u:
  lastline = ""
  for count, line in enumerate(u.readlines()):
    if count != 0:  # do not delay on first item outputted
      time.sleep(4)  # 4 sec delay so user can read before next text appears
    line = str(line).strip("\n")
    print(' ' * (len(lastline) + 1), end='\r')  # clear last line
    print(line, end='\r')
    lastline = line
    cursor.hide()
cursor.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM