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")
Related
This question already has answers here:
How do I write output in same place on the console?
(9 answers)
Closed 3 years ago.
I would print the cpu usage with this simple python script. I would write the result, erase that row and re-write on the same line as like as windows shell does with some commands. Is it possible?
import psutil #import tsutil
import time
def printit():
while(1):
print(psutil.cpu_percent())
time.sleep(3)
printit()
This print line per line. I would the result always change on the same line
Use carriage return on print function
import psutil
import time
import sys
def printit():
while(1):
print('{:06.2f}'.format(psutil.cpu_percent()), end='\r')
time.sleep(3)
printit()
Updating: Using \r will break if the strings differ on size, format can fix this
yes, use print(psutil.cpu_percent(), end=' ')
you also need to flush stdout, because the content won't actaully be printed on screen unless you print a newline char.
try this:
import psutil
import time
import sys
def printit():
while(1):
print(psutil.cpu_percent(), end=' ')
sys.stdout.flush()
time.sleep(3)
printit()
I am making a text based game and I am trying to print this code one character at a time on each column.
'''###############
Let us begin...
###############'''
I can't figure out how to make it come out one column at a time.
Well, I still felt like answering this despite the vagueness of your question. Maybe this is what you are looking for, this prints one column at a time (one character per row):
import subprocess
import platform
from time import sleep
def clear_screen():
# thanks to: https://stackoverflow.com/a/23075152/2923937
if platform.system() == "Windows":
subprocess.Popen("cls", shell=True).communicate()
else:
print("\033c", end="")
# obviously you can create a function to convert your string into this
# list rather than doing it manually like I did, but that is another question :p.
views = ['#\nh\n#', '##\nhe\n##', '###\nhel\n###', '####\nhell\n####', '#####\nhello\n#####']
for view in views:
clear_screen()
print(view)
sleep(0.5)
If you are already doing print(c, end='') for each character in you string, just add flush=True to the call to print(). The sleep call will introduce enough delay so that you can see the characters print one at a time:
>>> import time
>>> s = '''###############
... Let us begin...
... ###############'''
>>> for c in s:
... print(c, end='', flush=True)
... time.sleep(0.1)
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"))
I want to print out i in my iteration on Jupyter notebook and flush it out. After the next iteration, I'll print the next i. I tried solutions from this question and this question, however, it just print out 0123...9 without flushing the output for me. Here is my working code:
import sys
import time
for i in range(10):
sys.stdout.write(str(i)) # or print(i, flush=True) ?
time.sleep(0.5)
sys.stdout.flush()
these are my setup: ipython 5.1, python 3.6. Maybe, I missed something in the previous solution?
#Try this:
import sys
import time
for i in range (10):
sys.stdout.write('\r'+str(i))
time.sleep(0.5)
'\r' will print at the beginning of the line
The first answer is correct but you don't need sys package. You can use the end parameter of the print function. It specifies what to print at the end, and its default value is \n(newline) (docs1, docs2). Use \r(carriage return) instead.
import time
for i in range (10):
print(i, end="\r")
time.sleep(0.5) # This line is to see if it's working or not
Try this
for i in range (10):
print("\r", end=str(i))
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