2017-12-09 1 views
1

이동하거나 새로 만들 파일을위한 디렉토리를 모니터링하고 있습니다. 새 파일을 감지하면 파일을 처리 할 다른 python 스크립트를 호출합니다.In_closted_write 및 in_moved_to 이벤트를 모니터링하기 위해 python inotify

#!/usr/bin/python 

import os 
import signal 
import sys 
import logging 
import inotify.adapters 
import subprocess 

_DEFAULT_LOG_FORMAT = '' 

_LOGGER = logging.getLogger(__name__) 

def _configure_logging(): 
    _LOGGER.setLevel(logging.DEBUG) 

    ch = logging.StreamHandler() 

    formatter = logging.Formatter(_DEFAULT_LOG_FORMAT) 
    ch.setFormatter(formatter) 

    _LOGGER.addHandler(ch) 

def exit_gracefully(signum, frame): 
    signal.signal(signal.SIGINT, original_sigint) 
    sys.exit(1) 

    signal.signal(signal.SIGINT, exit_gracefully) 

def main(): 
    i = inotify.adapters.Inotify() 

    i.add_watch(b'/home/sort/tmp') 

    try: 
     for event in i.event_gen(): 
      if event is not None: 
       if 'IN_MOVED_TO' in event[1] or 'IN_CLOSE_WRITE' in event[1]: 
        (header, type_names, watch_path, filename) = event 
        _LOGGER.info("%s" #"WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s " 
         #"WATCH-PATH=[%s]" 
         "FILENAME=%s" + "/" + "%s", 
         type_names,#header.wd, header.mask, header.cookie, header.len, type_names, 
         watch_path.decode('utf-8'), filename.decode('utf-8')) 
       fnp = str(event[2] + "/" + event[3]) 
       print fnp 
       proc = subprocess.Popen([orgpath, fnp], stderr=subprocess.STDOUT, bufsize=1) 
       #proc.communicate() 
    finally: 
     i.remove_watch(b'/home/sort/tmp') 

if __name__ == '__main__': 
    _configure_logging() 

    orgdir = os.path.dirname(os.path.realpath(sys.argv[0])) 
    orgpath = os.path.join(orgdir, "organize.py") 

    original_sigint = signal.getsignal(signal.SIGINT) 
    signal.signal(signal.SIGINT, exit_gracefully) 
    print("Watching /home/sort/tmp for new files") 
    main() 

최종 목표는 메타 데이터를 긁어 API를 호출 할 때 한 번에 하나의 파일 만 처리하는 것입니다. 단기간에 API를 여러 번 호출하면 API 키가 금지되거나 일시적으로 차단 될 수 있습니다.

바로 지금 하나 이상의 파일을 모니터링 디렉토리에 복사하면 스크립트는 각 파일에서 동시에 호출됩니다. 그것은 여전히 ​​너무 빨리 실행중인 경우 API를 스로틀에, 당신은 타이머를 넣을 수 있습니다

for files in directory: 
    ...code that runs the python file 

답변

0

봅니다 .. 파이썬 파일을 실행하는 루프를 넣어 호출

import time 
for files in directory: 
    ...code that runs the python file 
    time.sleep(5) 
+0

겠습니까 for 루프는 orgpath 또는 하위 프로세스로 이동합니까? –

+0

아마 proc/subprocess하지만 너무 확실하지 않을 수 있습니다 .. 어쩌면 그것의 main() 함수 .. 100 % 확실하지 않기 때문에 어떻게 작동하고 내가 organise.py 무엇을 알지 못하기 때문에 그것을 복제 할 수 없습니다 .. – johnashu

+0

oraganize .py는 아직 완성되지 않았지만 현재 형태로 완성됩니다. –

관련 문제