0

I want to change a string on the console while it's outputted.

For example I can take a string such as "test" and output each character on the console with this:

for c in "test":
    sys.stdout.write(c)
    time.sleep(1)

#<= t
#<= te
#<= tes
etc..

But what if I wanted to take that output and change it while it was on the screen? For example, what if I wanted to capitalize each letter in the string while something runs in the background (kinda like a progress bar). So it would end up looking like this:

#<= Test
#<= tEst
#<= teSt
#<= tesT

Over and over again until whatever I'm downloading or running is finished. How can I go about changing the string itself on the console?


Seeing how this was duplicated I'll rephrase it.

I want to take the string that I have test and use (probably) stdout.flush() or something along those lines and capitalize each letter of that string while something runs in the background, so for example:

def download():
   # download something using requests(stream=True)
   while chunk_downloading:
       sys.stdout.write("test")
       # do something here to where it will run through the string and capitalize each letter
       sys.stdout.flush()

The output of this should look something along these lines (on one singular line):

test -> Test -> tEst -> teSt -> tesT -> test -> etc..
owasp
  • 45
  • 1
  • 5
  • 1
    You'll probably want to look into flushing stdout – Tom Wyllie Jul 19 '17 at 15:02
  • Take a look here https://stackoverflow.com/questions/6169217/replace-console-output-in-python – EsotericVoid Jul 19 '17 at 15:02
  • 3
    Possible duplicate of [Replace console output in Python](https://stackoverflow.com/questions/6169217/replace-console-output-in-python) – Tom Wyllie Jul 19 '17 at 15:02
  • Lemme rephrase my question one second, I know how to do `stdout` and all that good stuff, make progress bars, etc.. I want to change the output of the string AS it's on the screen if that makes any sense? Like take the string `test` and capitalize each letter one after another while something runs in the background @TomWyllie – owasp Jul 19 '17 at 15:05

2 Answers2

0

You can print 'r' at the beginning of the string to write to the beginning of the line, and if you don't put a '\n' at the end it won't go to the next one. Then you can do sys.stdout.flush(). If you put the sleep statement after the flush, it will change the string as it's on the screen. Try it out!

Cary Shindell
  • 1,336
  • 8
  • 25
0

As you said you will just show a kind of loading progress but you won't load your letter while the uppercase is shown.

The only thing you can do is to display the uppercase before showing the lowercase. Just show c.capitalize() before sleeping for 1sec