print without newline

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shubhangi s
    New Member
    • Feb 2012
    • 2

    print without newline

    Hi,
    I have facing an issue with python while printing a characher without new line.
    I want to print a "." to show progress of a search operation.

    Simple code to demonstrate the problem is

    Code:
    import time
    for i in range(10):
        print(".",end="")
        time.sleep(10)
    I am expecting to see a "." after every sleep/for every iteration. However I can see it only when the loop ends or i kill the run.

    Output :

    c:\Python30>pyt hon.exe c:\Users\ss001\ Desktop\PythonS cript\try.py
    ..Traceback (most recent call last):
    File "c:\Users\ss001 \Desktop\Python Script\try.py", line 4, in <module>
    time.sleep(10)
    KeyboardInterru pt
    Last edited by bvdet; Feb 22 '12, 04:28 PM. Reason: Please use code tags when posting code.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Instead of using print, write to sys.stdout and flush the buffer each iteration.
    Code:
    import sys, time
    
    for i in range(25):
        sys.stdout.write(".")
        sys.stdout.flush()
        time.sleep(.1)
    print

    Comment

    • Shubhangi s
      New Member
      • Feb 2012
      • 2

      #3
      Thanks very much...that worked ....

      Comment

      Working...