2017-06-22 64 views
2

我正在使用Raspberry Pi 3進行家庭自動化項目,並且需要在txt文件更改時運行一些python腳本。有沒有辦法看文件是否改變? (目前我使用如果有什麼變化,但它的效率不高,這不斷地打開TXT並檢查一個Python腳本,它有時會導致問題。 提前感謝!更改txt文件時運行python腳本

+2

[看門狗(https://pypi.python.org/pypi/watchdog/0.8.3)應告訴你何時有文件更改 – inspectorG4dget

+0

txt文件是否可以更改? –

+0

不,客戶端在需要時更改值。 – Chris

回答

1

如果你想報告中的局部變化到單個文件所謂foo.txt你可以使用watchdog(這是一種皮膚過度的inotify,或等價物)這樣的目錄:

from time import sleep 
from watchdog.observers import Observer 
from watchdog.events import FileSystemEventHandler 

class Handler(FileSystemEventHandler): 
    def on_modified(self, event): 
     if event.src_path == "./foo.txt": # in this example, we only care about this one file 
      print ("changed") 

observer = Observer() 
observer.schedule(Handler(), ".") # watch the local directory 
observer.start() 

try: 
    while True: 
     sleep(1) 
except KeyboardInterrupt: 
    observer.stop() 

observer.join()