浏览代码

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 12 年之前
父节点
当前提交
153c2cc8db
共有 1 个文件被更改,包括 14 次插入7 次删除
  1. 14 7
      15-exceptions.md

+ 14 - 7
15-exceptions.md

@@ -178,19 +178,23 @@ Save as `finally.py`:
 ~~~python
 ~~~python
 import time
 import time
 
 
+f = None
 try:
 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()
         line = f.readline()
         if len(line) == 0:
         if len(line) == 0:
             break
             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:
 except KeyboardInterrupt:
-    print('!! You cancelled the reading from the file.')
+    print("!! You cancelled the reading from the file.")
 finally:
 finally:
-    f.close()
-    print('(Cleaning up: Closed the file)')
+    if f:
+        f.close()
+    print("(Cleaning up: Closed the file)")
 ~~~
 ~~~
 
 
 Output:
 Output:
@@ -216,6 +220,9 @@ Observe that the `KeyboardInterrupt` exception is thrown and the
 program quits. However, before the program exits, the finally clause
 program quits. However, before the program exits, the finally clause
 is executed and the file object is always closed.
 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 ##
 ## The with statement ##
 
 
 Acquiring a resource in the `try` block and subsequently releasing the
 Acquiring a resource in the `try` block and subsequently releasing the