我在嘗試下面的python代碼來模擬* nix系統的'tail'命令。Python生成器:錯誤只能在評論後纔可見
import sys
def tail(f):
print 'in tail with ',f
f.seek(0,2)
while True:
line = f.readline()
if not line:
time.sleep(0.1)
continue
yield line
if(len(sys.argv) >= 2):
print 'calling tail'
tail(open(sys.argv[1],'r'))
else:
print 'Give file path.\n'
我做了一個錯誤(錯過了導入時間模塊)。然而,奇怪的是沒有錯誤被拋出,程序默默地放棄。 輸出(前評論):
$ python tail.py /var/log/dmesg
calling tail
但是,如果我評論後續的使用時間模塊的一個線,誤差不會拋出。
import sys
def tail(f):
print 'in tail with ',f
f.seek(0,2)
while True:
line = f.readline()
if not line:
time.sleep(0.1)
# continue
# yield line
if(len(sys.argv) >= 2):
print 'calling tail'
tail(open(sys.argv[1],'r'))
else:
print 'Give file path.\n'
輸出(評論後)
$ python tail.py /var/log/dmesg
calling tail
in tail with <open file '/var/log/dmesg', mode 'r' at 0x7fc8fcf1e5d0>
Traceback (most recent call last):
File "tail.py", line 14, in <module>
tail(open(sys.argv[1],'r'))
File "tail.py", line 8, in tail
time.sleep(0.1)
NameError: global name 'time' is not defined
誰能請解釋爲什麼錯誤沒有得到的情況下,拋出一個(評論)之前?解釋者一旦出現該錯誤,不應該拋出錯誤嗎?
修正程序:
import sys
import time
def tail(f):
print 'in tail with ',f
f.seek(0,2)
while True:
line = f.readline()
if not line:
time.sleep(0.1)
continue
yield line
if(len(sys.argv) >= 2):
print 'calling tail'
t = tail(open(sys.argv[1],'r'))
for i in t:
print i
else:
print 'Give file path.\n'
輸出:
$ python tail.py hello.txt
calling tail
in tail with <open file 'hello.txt', mode 'r' at 0x7fac576b95d0>
hello there 1
hello there 2
hello there 3
感謝您的答覆。
if條件是否滿足(在第二次通話中)只有當你不屈服時才行? – Peaceful