現在、ログファイルを使用しています。私の必要性は、指定された期間、たとえば 10 秒間、ファイルを 1 行ずつ読みたいということです。Pythonでこれを達成する方法があれば、誰か助けてもらえますか?
2 に答える
1
コード
from multiprocessing import Process
import time
def read_file(path):
try:
# open file for writing
f = open(path, "r")
try:
for line in f:
# do something
pass
# always close the file when leaving the try block
finally:
f.close()
except IOError:
print "Failed to open/read from file '%s'" % (path)
def read_file_limited_time(path, max_seconds):
# init Process
p = Process(target=read_file, args=(path,))
# start process
p.start()
# for max seconds
for i in range(max_seconds):
# sleep for 1 seconds (you may change the sleep time to suit your needs)
time.sleep(1)
# if process is not alive, we can break the loop
if not p.is_alive():
break
# if process is still alive after max_seconds, kiil it!
if p.is_alive():
p.terminate()
def main():
path = "f1.txt"
read_file_limited_time(path,10)
if __name__ == "__main__":
main()
ノート
1 秒ごとに「ウェイクアップ」して、開始したプロセスがまだ生きているかどうかを確認する理由は、プロセスが終了したときにスリープ状態を維持できないようにするためです。プロセスが 1 秒後に終了した場合、9 秒間スリープするために時間を無駄にします。
于 2013-10-24T07:02:57.730 に答える