Francisco Vargas
Francisco Vargas

Reputation: 652

Print with no new line python

I have checked out the possible duplicates nonetheless they are not working out for me.

What I am trying to do is rotate a numpy array and I want to see this as an animation in the terminal:

if __name__ ==  "__main__":
o = np.ones((10,10))
while True:
    for i in xrange(361):
        sys.stdout.write(repr(rot_position(o, i)))

Tried print followed by a comma and it does not work either. How can I make it always print on the same line (that works on python 2.7x)?

Upvotes: 2

Views: 4452

Answers (4)

ChickenFeet
ChickenFeet

Reputation: 2813

Erase and reprint the edited line with:

def clear_line():
    sys.stdout.write("\033[F") #back to previous line
    sys.stdout.write("\033[K") #clear line

then you can do something like:

print("Installing... | ")
time.sleep(0.3)
clear_line()
print("Installing... / ")
time.sleep(0.3)
clear_line()
print("Installing... - ")
time.sleep(0.3)
clear_line()
print("Installing... \ ")

This will produce a spinning animation. You could do something similar with your numpy array.

Another example:

print("1")
print("2")
clear_line():
print("3")

Which outputs:

1
3

Upvotes: 1

Somil
Somil

Reputation: 1941

you can use for python 2.7

print ("sometext", end="")

Upvotes: 0

Alpha Delta Foxtrot
Alpha Delta Foxtrot

Reputation: 81

you can always use (in Python 3.x):

print("sometext", end="")

anything for python 2.7 ?

Add this to the top of your code: from __future__ import print_function You can then use print as a function -- from @rwilson's comment.

Upvotes: 8

Craig Estey
Craig Estey

Reputation: 33601

The python 2.x "print with no newline" is: print("sometext"),

But, if you're trying to do what I think you're trying to do, between your while and for, add print("\r"),

Here's an example of a "ticker" program that illustrates what I'm talking about. Different, but I think it's applicable:

#!/usr/bin/python

import time
import sys

i = 0
hello = "hello world, goodbye universe "

while 1:
    print("\r"),

    cur = hello[i:] + hello[0:i]
    print("%s" % cur),
    sys.stdout.flush()

    i += 1
    if (i >= len(hello)):
        i = 0

    time.sleep(0.3)

Upvotes: 2

Related Questions