我想讀取文件,並在文件發生更改(即,對於外部程序)時,打印新的信息。 事情是這樣的:讀取外部文件並等待Python中的更改
import sys, os
with open('file.txt', 'r') as f:
fid = f.fileno()
r = os.fdopen(fid)
while True:
print r.read()
當我做:
echo "Hello world!" > file.txt
的Python腳本顯示:
> Hello world!
非常感謝。
編輯: 解決辦法:
time = os.path.getmtime('file.txt')
while True:
if (time <> os.path.getmtime('file.txt')):
with open('file.txt', 'r') as f:
info = f.read()
print "Readed: " + info
time = os.path.getmtime('file.txt')
看這個https://github.com/seb-m/pyinotify – Deck