Parcourir la source

Adding flush=True for print()

Based on:

#+BEGIN_QUOTE
From: cs.wzpan@gmail.com
Suggestion: Hello Swaroop,

Nice tutorial on Python! Definitely be my introduction to Python.

One comment though: in the [Python : Exceptions]
(http://swaroopch.com/notes/python_en-exceptions/) session I think
you'd better modify one line in the finally.py from "print(line,
end='')" to "print(line, end='', flush=True)" to make sure that the
screen will output something every 2 seconds. Otherwise in my machine
I cannot see the output before I press my keyboard or the counting
loop ends.
#+END_QUOTE
Swaroop C H il y a 12 ans
Parent
commit
153c2cc8db
1 fichiers modifiés avec 14 ajouts et 7 suppressions
  1. 14 7
      15-exceptions.md

+ 14 - 7
15-exceptions.md

@@ -178,19 +178,23 @@ Save as `finally.py`:
 ~~~python
 import time
 
+f = None
 try:
-    f = open('poem.txt')
-    while True: # our usual file-reading idiom
+    f = open("poem.txt")
+    while True:  # our usual file-reading idiom
         line = f.readline()
         if len(line) == 0:
             break
-        print(line, end='')
-        time.sleep(2) # To make sure it runs for a while
+        print(line, end="", flush=True)
+        time.sleep(2)  # To make sure it runs for a while
+except FileNotFoundError:
+    print("Could not find file poem.txt")
 except KeyboardInterrupt:
-    print('!! You cancelled the reading from the file.')
+    print("!! You cancelled the reading from the file.")
 finally:
-    f.close()
-    print('(Cleaning up: Closed the file)')
+    if f:
+        f.close()
+    print("(Cleaning up: Closed the file)")
 ~~~
 
 Output:
@@ -216,6 +220,9 @@ Observe that the `KeyboardInterrupt` exception is thrown and the
 program quits. However, before the program exits, the finally clause
 is executed and the file object is always closed.
 
+Note that we use `flush=True` in the call to `print()` so that it
+prints to the screen immediately.
+
 ## The with statement ##
 
 Acquiring a resource in the `try` block and subsequently releasing the