0

I have three outputs and I want to replace it in every 3 seconds.

With this code it's printing only the c:

import sys

import time

a = 1

b = 5

c =10

while True:

  sys.stdout.write("\r" + str(a))

  sys.stdout.write("\r" + str(b))

  sys.stdout.write("\r" + str(c))

  time.sleep(3)

  a += 1

  b+=1

  c+=1

  sys.stdout.flush()

Does anybody have an alternative to print all of them in 3 lines?

vargaking
  • 51
  • 1
  • 7

4 Answers4

1

all the above correct. Just make sure to create some endpoint to the While loop.

import sys 
import time
import os 

def clear():
    os.system( 'cls' )

a = 1
b = 5
c =10

while c<20:
  sys.stdout.write("\r" "****************************\n") 
  sys.stdout.write("\r" "This is Run : " + str(a) + "\n")
  sys.stdout.write("\r" "****************************\n")
  sys.stdout.write("\r" " This is a : " + str(a) +  "\n This is b :" +  str(b) + "\n This is C:"  +str(c) + "\n" )

  time.sleep(2)

  a += 1
  b+=1
  c+=1
  sys.stdout.flush()
  clear()

Based on your reply I think this is what you looking for. When I run it from console it clears the outputs.

Galileo
  • 81
  • 1
  • 4
1

This is happening because the command sys.std.write is overwriting the outputs. The outputs are only getting cleared when you call sys.stdout.flush(). Although this command also just clears the data buffer which is the temporary region where python stores data temporarily. Therefore, hitting it will just put your cursor to new line i.e. equivalent to \n new line character.

So, basically you need to write a \n the new line character at the end of the string to show all inputs.

Also, if you want to clear the console you may use os.system('clear').

You may refer the following code for a cleaner output.

import os
import sys
import time

a, b, c = 1, 5, 10

while True:
    sys.stdout.write(f"a:{a} b:{b} c:{c}\n")
    time.sleep(3)
    a += 1
    b += 1
    c += 1
    #clear console
    os.system('clear')
Mohit S
  • 57
  • 1
  • 3
0

No, it is printing a, immediately overwriting it with b and then with c, so c is all you see. The only way (aside from utilizing curses or some other advanced terminal capabilities) to have all three visible is to print them in single line like this:

sys.stdout.write("\r{} {} {}".format(a,b,c))
Błotosmętek
  • 12,717
  • 19
  • 29
0

The reason you are only seeing the c as you mentioned, is because it is the last thing you wrote before calling sys.stdout.flush()

If you remove the part where sys.stdout.write("\r" + str(c)) you will then see b

As @Błotosmętek mentioned and answered before me, you can format the required output and then perform the flush.

r1024
  • 11
  • 4