I am using the following line to print the time at the start of my code.
print (time.strftime("%H:%M:%S"))
I am also using the same command during long 'for' loops so that I can predict how long it will take my code to run. (I am doing heat flow modeling with a lot of time steps.)
The time at the start doesn't print until the first print time.strftime() command in the 'for' loop prints. Both are the correct times.
How can I get it to print when the code starts, rather than when the next print command seems to flush it out?
What you're trying to do is to flush out the print buffer, which looks like this in Python 2:
import sys
print(time.strftime("%H:%M:%S"))
sys.stdout.flush()
In Python 3, it's even easier:
print(time.strftime("%H:%M:%S"), flush=True)
I get different time in my for loop whenever i print time.strftime("%H:%M:%S") I am using python 3.5
import time
print ('Started at :' + time.strftime("%H:%M:%S"))
for x in range(5):
print (x)
time.sleep(1)
print ('Current time is:' + time.strftime("%H:%M:%S"))
print ('Script Ended at :' + time.strftime("%H:%M:%S"))
Related
So i have a code of a timer and When a person puts in the number i just want the timer to start and inputted number to not be visible.Code is something like
s=int(input("enter time in sec"))
countdown(s)
so the output is :
enter time in sec 5
0:4
0:3
0:2
0:1
0:0
time up
What i want is to first remove "enter time in sec 5" then when 0:4 prints i want to print 0:3 in its place not below it.
I tried Python deleting input line and copy pasted this on the code like so
s = int(input("enter time in sec "))
print ('\033[1A\033[K')
countdown(s)
and nothing seemed to happen, don't if im wrong in the implementation or it didn't work.
Edit:-
Tried both
os.system('cls')
and
print ('\033[1A\033[K')
neither seemed to work
my code,
def time_format(inp):
import os
m,s=divmod(inp,60)
#os.system('cls')
print ('\033[1A\033[K')
...code for printing time below...
Edit:- im on windows and am using Idle.
neither of the two work
You didn't specify what OS you use but if you target Linux it could
be:
#!/usr/bin/env python3
import time
def countdown(seconds):
for i in range(seconds, -1, -1):
# move to the beginning of the line and remove line
print("\r\033[K", end='', flush=True)
print(f"\r{i}", end='', flush=True)
time.sleep(1)
print("\nTime's up!")
s = int(input("enter time in sec: "))
# move one line up
print("\033[1A", end='', flush=True)
countdown(s)
It works like that:
See accepted answer of: How to clear the interpreter console?
os.system('cls') works on Windows, while
os.system('clear') works on Linux
Got a pop saying I shouldn't delete answered question therefore answering it myself.
I believe both the
print("\033[1A", end='', flush=True)
and
os.system('cls')
works. The issue is that there is no option/method to do it on IDLE. because i tried both the methods work if i double click and run the file as is but none work on IDLE
I have the following loop which prints a period after each iteration:
for i in range(3):
time.sleep(1)
print('.')
This runs exactly as expected: a period is printed to the terminal on a new line in 1 second increments
. # after 1 seconds
. # after 2 seconds
. # after 3 seconds
I want to change the output to print periods to the same line (so the output is more compact and easier to read). However, I have a problem when I change the code to the following:
for i in range(3):
time.sleep(1)
print('.', end='')
In this case, the single line of periods only print all at once when the for loop is complete:
... # all after 3 seconds
Am I doing something wrong here or there a limitation with the python print statement?
By default, terminal output won't appear until a newline is printed.
You can force partial lines to appear immediately by adding flush=True to the print call.
Here, this will help you:
import time
for i in range(3):
time.sleep(1)
print(".", end="", flush=True)
print("")
Edit
In case you are using python2, be sure to add
from __future__ import print_function
as the first statement to your script.
I want to code simple digital clock in the python shell. I want to avoid using tkinter if possible. This is what I currently have;
import time
while True:
from datetime import datetime
now = datetime.now()
print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second))
time.sleep(1)
This produces a recurring print out, something like this;
06/29/16 23:08:32
06/29/16 23:08:33
06/29/16 23:08:34
I know this is crude, I'm still learning. I just want one line with a "ticking" digital clock in the shell. I'm using python 3.5.1 on idle and windows 10.
If this isn't possible, I'd very much like to know why.
Kindest thanks
If you're just printing out a fixed length output like this each time, you can use the carriage return character to rewind to the start of the line, as long as you don't print a newline. Example:
# Note trailing comma, that suppresses the newline in Python
print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second)),
# Now rewind back to the start of the line. Again, not trailing comma
print("\r"),
Now, you may also notice that nothing is ever printed to the screen. This is because standard out is buffered, so you can flush with this:
# At the top...
import sys
# In the loop, after the first print
sys.stdout.flush()
This all works as follows. Imagine that there is actually a cursor on screen. You first print out the time with the first print (and the flush), then you move the cursor back to the start of the line with print("\r"),. This doesn't actually remove any of the characters, it just moves the cursor. You then write the next time out again. Because it nicely happens to be the exact same length, the time gets written out again, replacing the old characters.
The resulting script is then as follows:
import time
import sys
while True:
from datetime import datetime
now = datetime.now()
print ("%s/%s/%s %s:%s:%s" % (now.month,now.day,now.year,now.hour,now.minute,now.second)),
sys.stdout.flush()
print("\r"),
time.sleep(1)
If you want finer grained control over what's going on, you can start using the curses library, but I imagine that's overkill for what you're trying to do here.
EDIT: As #PadraicCunningham mentioned in the comments, the correct syntax to suppress newline printing in Python 3 and force the contents to flush to the screen is the following:
print("hello", flush=True, end="")
Also, as #AlexHall mentions, the print statement does not actually print a fixed width statement; so to do this, we should use strftime() instead.
Therefore the correct program is:
import time
while True:
from datetime import strftime
print (strftime("%m/%d/%Y %H:%M:%S"), end="", flush=True)
print("\r", end="", flush=True)
time.sleep(1)
All you need is:
from time import strftime
while True:
print (strftime("%m/%d/%Y %H:%M:%S"), end="", flush=True)
print("\r", end="", flush=True)
time.sleep(1)
tried this in repl.it, this worked for me...( added commas & now.strftime )
import time
from datetime import datetime
while True:
now = datetime.now()
print (now.strftime("%m/%d/%Y %H:%M:%S"), end="", flush=True),
print("\r", end="", flush=True),
time.sleep(1)
The following code is working for me.
from time import sleep
from datetime import datetime
while True:
now = datetime.now()
stdout.write(now.strftime("\r%m/%d/%Y %H:%M:%S")),
stdout.flush()
sleep(1)
stdout.write("\n")
You could set end= " " to remove newlines and add a carriage return i.e.:
'\r'
Therefore the correct program which should work for you is:
from datetime import datetime
import time
while True:
now = datetime.now()
print("\r%s/%s/%s %s:%s:%s" % (now.month, now.day, now.year, now.hour, now.minute, now.second), end='')
time.sleep(1)
print('')
A slight improvement on the above answers (removing the trailing comma; and changing end from "" to "\r" to do the carriage return as part of a single print statement.
import time
from datetime import datetime
while True:
now = datetime.now()
print (now.strftime("%m/%d/%Y %H:%M:%S"), end="\r", flush=True)
time.sleep(1)
ImportError: cannot import name 'strftime' from 'datetime' (/usr/lib/python3.7/datetime.py) So, use the following code:
import time, sys
while True:
from datetime import datetime
now = datetime.now()
showClock =" %s:%s:%s" % (now.hour,now.minute,now.second)
print(showClock, end="\r")
I want to make (for fun) python print out 'LOADING...' to console. The twist is that I want to print it out letter by letter with sleep time between them of 0.1 seconds (ish). So far I did this:
from time import sleep
print('L') ; sleep(0.1)
print('O') ; sleep(0.1)
print('A') ; sleep(0.1)
etc...
However that prints it to separate lines each.
Also I cant just type print('LOADING...') since it will print instantaneously, not letter by letter with sleep(0.1) in between.
The example is trivial but it raises a more general question: Is it possible to print multiple strings to one line with other function being executed in between the string prints?
In Python2, if you put a comma after the string, print does not add a new line. However, the output may be buffered, so to see the character printed slowly, you may also need to flush stdout:
from time import sleep
import sys
print 'L',
sys.stdout.flush()
sleep(0.1)
So to print some text slowly, you could use a for-loop like this:
from time import sleep
import sys
def print_slowly(text):
for c in text:
print c,
sys.stdout.flush()
sleep(0.5)
print_slowly('LOA')
In Python3, change
print c,
to
print(c, end='')
You can also simply try this
from time import sleep
loading = 'LOADING...'
for i in range(10):
print(loading[i], sep=' ', end=' ', flush=True); sleep(0.5)
from time import sleep
myList = ['Let this be the first line', 'Followed by a second line', 'and a third line']
for s in myList:
print(s) ; sleep(0.6)
If you've written a quite large program and want to add that feature, then overwrite the builtin function print
python_print = print
def print(txt):
text = str(txt)
for c in text:
python_print(c, end="", flush=True)
time.sleep(random.randint(2, 8)/100)
python_print()
This function ensures that
The output is flushed (no need of the sys module)
After one character was written, there is a delay of 0.02 to 0.08 seconds.
The actual behavior of the print function is kept (so you can make it print arrays and modules) - because of the str() call, though there are some exceptions.
What this function cannot do:
You can't call print like this anymore because it only takes one argument:
print("Hello", "World")
Feel free to add that feature or have a look at someone implemented that:
https://book.pythontips.com/en/latest/args_and_kwargs.html
Oh and if you haven't noticed yet - use python_print() if delayed text is inapropriate in some cases.
I wonder why python_print is not shallow-cloned. May anyone explain?
--
Someone implemented that :)
Someone has called my approach (I think especially the *args) cute and worked for at least 30 minutes to get something even better which is considerably larger (please, don't call it bloated though). I didn't test it, but it seems working well to my eyes.
So with that code you'll be able to use print like print("Hello", "World") again.
Credits to: #MarcinKonowalczyk =>
https://gist.github.com/MarcinKonowalczyk/48a08fe2492b88df184decf427fd2caf
Thank you for taking your time.
Now Run a Function While Loading
In order to run something (otherwise Loading would be useless anyway I guess) while it's printing, you can use the threading module.
So, without further ado, let's quickly get started.
import threading
def load():
# do I/O blocking stuff here
threading.Thread(target=load).start() # returns the thread object
# and runs start() to launch the function load() non-blocking.
print("LOADING...")
You may consider removing the random delay from my function which is untypical for a LOADING... screen.
If you don't need to wait until the LOADING... is done to close the program easily with ctrl-c, you can change the daemon attribute to True. Please note that, if the main thread finishes, your other thread will stop forcefully.
Here's an example to how you could to that:
loadingThread = Threading.thread(target=load)
loadingThread.daemon = True
loadingThread.start()
print("LOADING...")
loadingThread.join() # wait for the loadingThread to finish
With this, the program will exit just fine, however you may have to catch KeyboardInterrupt:
try:
loadingThread.join()
except KeyboardInterrupt:
# cleanup stuff here or just *pass*
finally: # optional, runs *always*
# cleanup stuff here
Updated to print all the letters on one line.
from time import sleep
import sys
sys.stdout.write ('L') ; sleep(0.1)
sys.stdout.write ('O') ; sleep(0.1)
sys.stdout.write ('A') ; sleep(0.1)
...
sys.stdout.write ('\n')
etc...
or even:
from time import sleep
import sys
output = 'LOA...'
for char in output:
sys.stdout.write ('%s' % char)
sleep (0.1)
sys.stdout.write ('\n')
To type a string one letter at a time all you've got to do is this:
import sys
import time
yourWords = "whatever you want to type letter by letter"
for char in yourWords:
sys.stdout.write(char)
time.sleep(0.1)
import time
import sys
def code(text, delay=0.07):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(delay)
print()
Instead of print type code
I am trying to print a string letter by letter (with a pause in between each print) onto the terminal screen and I want it to all be on the same line.
I currently have this:
sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
print(l, end=" ")
sleep(0.1)
sleep(2)
for l in activ:
print(l, end=" ")
sleep(0.1)
For some reason this doesn't sleep in between prints in the loop, rather it seems to wait until the loop is complete before printing all of it out at once.
I want it to look like it is being "typed" on the screen in real time.
Any suggestions?
Thanks!
Zach
try flushing it
for l in activ:
print(l, end=" ")
sys.__stdout__.flush()
sleep(0.1)
no idea if it will work since I am assuming you are using py3x and it works fine in my system with or without the flush
flush just forces the output buffer to write to the screen ... normally it will wait until it has some free time to dump it to the screen. but sleep was locking it. so by flushing it you are forcing the content to the screen now instead of letting the internal scheduler do it ... at least thats how I understand it. Im probably missing some nuance
The following works:
import time
import sys
sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
sys.stdout.write(l);
time.sleep(0.1)
time.sleep(2)
print
for l in activ:
sys.stdout.write(l);
time.sleep(0.1)