For loop with time.sleep() [duplicate] - python

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I flush the output of the print function?
(13 answers)
Closed 2 years ago.
im a beginner at python and i've come across what is probably a simple problem.
I want the code below to print the "." x times, each .100 of a second after each other. This is what ive got, but it just prints it all at once after x * .100 seconds. It would also help if you could redirect me to something that explains why it dosnt work or if you explained why it dosnt work.
import time
for i in range(x):
print(".", end="")
time.sleep(.100)
Thanks in advance.
PS. If the code is completely wrong please say so.

Just printing doesn't mean that the content is flushed - i.e. it can still be in a buffer in your terminal or execution environment.
You can append flush=True to the arguments to print in python3 to make it flush the output as well:
import time
for i in range(x):
print(".", end="", flush=True)
time.sleep(.100)

Related

Is there a way to prevent automatic newline on python command line? [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 3 years ago.
I am making a command line game engine in python. However, when I attempt to print a command, it newlines and creates a jittery frame.
Adding the end attribute bogs down my computer and nearly crashes the shell. The dupe uses sys.stdout.write('') newline sys.stdout.flush or print'', or print('',end=''). all bog down shell and crash it. print('') doesn't bog down though which is weird.
#this is enough code to demonstrate the problem
while true:
print(' = === ===== ======= ========= =========== ============= YYYYYYYYYYY ================================================================================')
#crash issue
import sys
while True:
sys.stdout.write('mooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo')
sys.stdout.flush()
I expect the screen to fill, instead it wobbles up and down.
I am not sure if I understood your question correctly, but I’m thinking you do not want to print a new line with each call to the print() function.
If so, the print function has an optional argument end, that is set by default as \n (this, creating a new line if not specified otherwise). If you don’t want this to happen, you can simply use the print function as:
print(your_argument, end=“”)
Replacing your_argument with whatever you want to print out.

How to clear a screen in Python? [duplicate]

This question already has answers here:
How to clear the interpreter console?
(31 answers)
Clear terminal in Python [duplicate]
(27 answers)
Closed 3 years ago.
I am running on Python 3.7.1 and I've been trying to find a way to clear a screen of any previously printed messages. The problem is that os.system("cls") does nothing, it only makes a small window pop up for a fraction of a second, then it closes. I've tried to add a \n at the end and multiplying it by how many letters there are, still not working.
Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own.
We can use ANSI escape sequence but these are not portable and might not produce desired output.
# import only system from os
from os import system, name
# import sleep to show output for some time period
from time import sleep
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# print out some text
print('hello geeks\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call function we defined above
clear()
I don't think that there is a way, or at least have never seen one. However, there is a workaround which would look like
print "\n" * 100.
This will simply print 100 newlines, which will clear the screen for you.
You could also put it in a function
def cls(): print "\n" * 100
And then when you need it just call it with cls()

Python: Output while waiting for input [duplicate]

This question already has an answer here:
Exiting while loop by pressing enter without blocking. How can I improve this method?
(1 answer)
Closed 5 years ago.
So I currently have a thread that is outputting, and I need a way to handle input while still allowing output from the thread in the meantime.
Currently I have something like this
def thread_func():
while True:
print("Information")
threading.Thread(target=thread_func).start()
while True:
command = raw_input("Enter a command:")
#dostuff with command
My issue now is that my thread isn't printing anything. Or if it is it isn't showing up
Edit:
Found a solution here
Exiting while loop by pressing enter without blocking. How can I improve this method?
You want to use a Queue. New input will go into the back of the queue, and work will be started from the front.

Slow, word-by-word terminal printing in Python? [duplicate]

This question already has answers here:
How to print one character at a time on one line?
(4 answers)
Closed 9 years ago.
I'm writing a Python app involving a database. For the hell of it, I'm including an easter egg. If the user decides to nuke his database, all this from a terminal, he'll be prompted to confirm with a simple (y/n). But if he types DLG2209TVX instead, the lines from that scene of WarGames will print. Doubt anybody will ever find it unless they look through my source, but that's okay.
The problem is that simply printing the lines plays the scene way too fast and really just ruins it. I implemented a timer between each character's lines to slow things down, and it's better, but it still seems unnatural. Is there a standardized way to slowly print each word or character out instead of doing it lines at a time? Or should I just start adding timers between words?
Standardized? Not that I know of. But try this:
import random
import sys
import time
def slowprint(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush() # defeat buffering
time.sleep(random.random() * 0.1)
slowprint('Hello, world.')
Adjust the 0.1 to change the maximum delay between characters, and add lengthy time.sleep()s between lines to add more dramatic effect.
import sys
import time
for c in gettysburg_address:
sys.stdout.write(c)
sys.stdout.flush()
# 110 baud:
time.sleep( 8./110 )
# 300 baud:
# time.sleep( 8./300 )
You can also try curses.delay_output():
In [48]: import curses
In [49]: for x in "foo bar":
sys.stdout.write(x) #prints each char with a delay of 100ms
curses.delay_output(100)
....:
foo bar

progress of loop indicator [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python Progress Bar
I am running a for loop 10,000 times,
but inside the loop there are a lot of calculations going on.
I would like to print out a progress message to the console informing me how far along in the loop the program is how much longer I might have to wait.
the basic loop is
n = 10000
for i in range(n):
do_stuff_method()
if(i%100 == 0):
print (float(i)/n)*100,
This prints out a percentage message on the same line, but the problem is that the next thing that I print out is also printed out on the same screen. That, and since there are 99 prinouts, the console gets pretty wide and there is a lot of scrolling across.
What I would really like is for the console to print out the current % done, and an estimated time to finsih on the one line replace that which had been previously printed, so there doesn't have to be a lot scrolling.
Can this be done?
Cheers,
Davy
In your case you can do it simply by changing your print line to be:
print "\r{0}".format((float(i)/n)*100),
Or you can try it like this instead of print:
sys.stdout.write("\r{0}".format((float(i)/n)*100))
sys.stdout.flush()

Categories

Resources