Home > Software engineering >  "Typewriter"-like printing not working in CMD or py.exe, but works in VS Code Terminal
"Typewriter"-like printing not working in CMD or py.exe, but works in VS Code Terminal

Time:09-16

I'm studying software development and we've started using python, and for an exercise I wanted to make a "fancy" printing style. With some help from the internet I managed to get this to work in the terminal of VS Code, which I've been using- but when running the .py file on its own or through CMD, the loop is ran as many times as it should, and only then prints the output all at once.

from time import *
from random import *
from numbers import *

# Slow printing function- prints 1 character at a time
def slowPrint(line):
    for char in line: # For every character (char) in the string (line)
        t = uniform(0.03, 0.3)
        print(char,end="") # Print the character, end on nothing to ensure no spaces between characters
        sleep(t) # Sleep for t amount of seconds

# Conversation
slowPrint("Message 1."), sleep(0.5), slowPrint(" Message 2.\n")


input("Press enter;")

What I believe it should do, and what it does in the VS Code Terminal, is that it prints every character on its own, with a random delay between each character. I can't figure out what is making this different between VS Code and CMD.

I hope someone here knows this :> thanks in advance!

CodePudding user response:

Add flush=True to the print function:

print(char, end="", flush=True)

Basically flush well... flushes the data immediately instead of buffering it (w3schools reference to print function)

Also:
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.

  • Related