파이썬 코드를 따라 * nix 시스템의 '꼬리'명령을 시뮬레이트하려고했습니다.파이썬 생성기 : 주석 처리 후에 만 표시되는 오류
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
그러나, 오류가 던져 않습니다. 오류가 하나 (코멘트하기 전에) 경우에 던져지고되지 않은 이유를
$ 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
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'
출력? 통역관이 오는 즉시 오류가 발생해서는 안됩니까?
수정 프로그램 :
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