Sleep function not working after program is saved [duplicate] - python

This question already has answers here:
How can I flush the output of the print function?
(13 answers)
Closed 1 year ago.
I am using a time.sleep function to have my strings printed letter by letter, and it works perfectly while running inside pycharm, yet when I save the program and run it directly, the function does not take effect
def welcome():
greeting = random.choice(open_msg)
for i in range(len(greeting)):
print(greeting[i], end='')
time.sleep(0.15)
This is an example of what the code looks like

By default, Python's output is line-buffered. Therefore it won't print anything until you print a linefeed. To avoid this behavior, flush the output after each letter. Since Python 3.3, print() has an argument to do this. (For older versions, you need to sys.stdout.flush() after each print().)
print(greeting[i], end='', flush=True)
You can cause Python not to buffer by invoking it with the -u flag or by setting the environment variable PYTHONUNBUFFERED to any value. But these affect all output. It's better to use flush where you need it and leave other output buffered, because buffered is faster.
By the way, don't use range() when iterating over a string. Iterate over the string directly and you get the characters.
for c in greeting:
print(c, end='', flush=True)
# etc.

Ides can take longer to execute, amplifying the time.sleep() function
Maybe lengthen the time in the argument of time.sleep()

It should be working. Perhaps you forgot one of your imports? If so, here is the code, it is written well.
import random
import time
open_msg = ['hello', 'finished', 'chicken']
def welcome():
greeting = random.choice(open_msg)
for i in range(len(greeting)):
print(greeting[i], end='' )
time.sleep(0.15)
welcome()
``

Related

`time.sleep()` causing previous `print()` with `end=''` to delay [duplicate]

I have a python script that performs a simulation. It takes a fairly long, varying time to run through each iteration, so I print a . after each loop as a way to monitor how fast it runs and how far it went through the for statement as the script runs. So the code has this general structure:
for step in steps:
run_simulation(step)
# Python 3.x version:
print('.', end='')
# for Python 2.x:
# print '.',
However, when I run the code, the dots do not appear one by one. Instead, all the dots are printed at once when the loop finishes, which makes the whole effort pointless. How can I print the dots inline as the code runs?
This problem can also occur when iterating over data fed from another process and trying to print results, for example to echo input from an Electron app. See Python not printing output.
The issue
By default, output from a Python program is buffered to improve performance. The terminal is a separate program from your code, and it is more efficient to store up text and communicate it all at once, rather than separately asking the terminal program to display each symbol.
Since terminal programs are usually meant to be used interactively, with input and output progressing a line at a time (for example, the user is expected to hit Enter to indicate the end of a single input item), the default is to buffer the output a line at a time.
So, if no newline is printed, the print function (in 3.x; print statement in 2.x) will simply add text to the buffer, and nothing is displayed.
Outputting in other ways
Every now and then, someone will try to output from a Python program by using the standard output stream directly:
import sys
sys.stdout.write('test')
This will have the same problem: if the output does not end with a newline, it will sit in the buffer until it is flushed.
Fixing the issue
For a single print
We can explicitly flush the output after printing.
In 3.x, the print function has a flush keyword argument, which allows for solving the problem directly:
for _ in range(10):
print('.', end=' ', flush=True)
time.sleep(.2) # or other time-consuming work
In 2.x, the print statement does not offer this functionality. Instead, flush the stream explicitly, using its .flush method. The standard output stream (where text goes when printed, by default) is made available by the sys standard library module, and is named stdout. Thus, the code will look like:
for _ in range(10):
print '.',
sys.stdout.flush()
time.sleep(.2) # or other time-consuming work
For multiple prints
Rather than flushing after every print (or deciding which ones need flushing afterwards), it is possible to disable the output line buffering completely. There are many ways to do this, so please refer to the linked question.

Why does this for loop wait until the end of the iteration to print everything? [duplicate]

I have a python script that performs a simulation. It takes a fairly long, varying time to run through each iteration, so I print a . after each loop as a way to monitor how fast it runs and how far it went through the for statement as the script runs. So the code has this general structure:
for step in steps:
run_simulation(step)
# Python 3.x version:
print('.', end='')
# for Python 2.x:
# print '.',
However, when I run the code, the dots do not appear one by one. Instead, all the dots are printed at once when the loop finishes, which makes the whole effort pointless. How can I print the dots inline as the code runs?
This problem can also occur when iterating over data fed from another process and trying to print results, for example to echo input from an Electron app. See Python not printing output.
The issue
By default, output from a Python program is buffered to improve performance. The terminal is a separate program from your code, and it is more efficient to store up text and communicate it all at once, rather than separately asking the terminal program to display each symbol.
Since terminal programs are usually meant to be used interactively, with input and output progressing a line at a time (for example, the user is expected to hit Enter to indicate the end of a single input item), the default is to buffer the output a line at a time.
So, if no newline is printed, the print function (in 3.x; print statement in 2.x) will simply add text to the buffer, and nothing is displayed.
Outputting in other ways
Every now and then, someone will try to output from a Python program by using the standard output stream directly:
import sys
sys.stdout.write('test')
This will have the same problem: if the output does not end with a newline, it will sit in the buffer until it is flushed.
Fixing the issue
For a single print
We can explicitly flush the output after printing.
In 3.x, the print function has a flush keyword argument, which allows for solving the problem directly:
for _ in range(10):
print('.', end=' ', flush=True)
time.sleep(.2) # or other time-consuming work
In 2.x, the print statement does not offer this functionality. Instead, flush the stream explicitly, using its .flush method. The standard output stream (where text goes when printed, by default) is made available by the sys standard library module, and is named stdout. Thus, the code will look like:
for _ in range(10):
print '.',
sys.stdout.flush()
time.sleep(.2) # or other time-consuming work
For multiple prints
Rather than flushing after every print (or deciding which ones need flushing afterwards), it is possible to disable the output line buffering completely. There are many ways to do this, so please refer to the linked question.

Python3 how to clear previous prints while looping, flush? [duplicate]

This question already has answers here:
Replace console output in Python
(12 answers)
Closed 2 years ago.
I want to show only one item at the screen I guess this should be done with print(..., flush=True) but it don't work as I expected.
for i in range(0,100):
print(i, end='', flush=True)
Now I get a numbers like this 012345678.... and what I want to see at the screen is only one number without seeing previous prints so with first iteration it shows only 0 second shows only 1, I thought flush would do the trick but it didn't so where am I wrong?
You can use end='\r' as an argument to print(). \r escape sequence moves the cursor to the starting of the line. flush is not the correct argument for doing this.
Your code can be:
for i in range(0,100):
print(i, end='\r')
You can make use of os module to do the same
import os
import time
for i in range(100):
print(i)
time.sleep(1)
os.system("clear") # For Linux
#os.system("cls") # For Windows
I have used time.sleep() to make sure the effect is visible otherwise it executes very fast. You may make variations as per the need.

time.sleep not working per item in range or list [duplicate]

This question already has answers here:
How can I flush the output of the print function?
(13 answers)
Closed 2 years ago.
I was trying to make a code like this
def no(t=.001):
print("N", end='')
for i in range(1000):
print('o', end='')
time.sleep(t)
print()
So that when I call no() I would print a long "Nooooo...", waiting some time between each 'o'.
What happens instead is that the function halts, for the whole total time (1 second with the default argument), then prints the whole list.
Is this intended? And if not how should I obtain my intended effect?
What's happening here is that python is actually printing all the characters in exactly the same way that you intend - it writes the N, then an o per second to stdout. The issue is that the operating system does not display it because the file (stdout is a file) is not flushed. This typically automatically happens when \n is printed (by default, at the end of the printed string), but you'd overwritten that with end==''.
Luckily, print has an optional flush argument that you can use to force a flush. So you should be able to fix your behavior with this:
def no(t=.001):
print("N", end='', flush=True)
for i in range(1000):
print('o', end='', flush=True)
time.sleep(t)
print()

print without new line only appear after I write something else [duplicate]

This question already has answers here:
Printing on the same line with time.sleep()
(2 answers)
Closed 8 years ago.
I'm using Python 2.7.3 and I running the code below
def t2():
print "Waiting...",
time.sleep(3)
print "done."
time.sleep(1)
print "test"
time.sleep(2)
print "testing"
When I run this code, the string "Waiting... done." appear at same time. It's like the sleep(2) is before the first print.
If I don't use comma to remove new line (Like "test" and "testing" examples), sleep function works ok but I get "Waiting..." and "done." on different lines.
I already tried:
for i in range(0, 5): time.sleep(1)
and
subprocess.check_output(["sleep", "5"])
What can I do?
Thank you.
Depending what you are working with data doesn't necessarily get written right away. In particular,
display output often waits until it receives a newline before printing anything.
flush() makes sure it all gets written right now.
Background reading that helps explain better than I can:
Usage of sys.stdout.flush() method

Categories