0

FULL CODE:

import sys
import time

counter = 0

while True:
    sys.stdout.write(str(counter))
    time.sleep(1)
    sys.stdout.truncate()
    counter += 1

PART THAT MATTERS

sys.stdout.truncate()

QUESTION(S)

Why does sys.stdout.truncate() return an error? How can I truncate sys.stdout if sys.stdout.truncate() will not work?

OPERATING SYSTEM AND MORE INFO

Operating System: Windows

Operating System Version: Windows 10

Programming Language: Python

Programming Language Version: Python 3.6

Other Details: Run from command line

MilkyWay90
  • 2,023
  • 1
  • 9
  • 21

1 Answers1

1

sys.stdout is a a file object which corresponds to the interpreter’s standard output and does not have a truncate() method:

https://docs.python.org/3/library/sys.html#sys.stdout

It seems like you want to create status bar style output. This should work in Python3:

import time

counter = 0

while True:
   print("{}".format(counter), end="\r")
   time.sleep(1)
   counter += 1

See How to overwrite the previous print to stdout in python? for more info

d g
  • 1,594
  • 13
  • 13
  • Thank you, I will check if it works, because I remember hearing that \r only works for UNix-based operating systems. – MilkyWay90 Nov 07 '18 at 20:26
  • It works! The thing was that I was making a text-based game, and don't want to keep on using os.system("cls"), but I need to truncate all of sys.stdout for that, but still, this is useful, for loading screens. Thank you! – MilkyWay90 Nov 07 '18 at 20:28
  • Glad I could help! – d g Nov 07 '18 at 22:33