下面是一个有效的python脚本,该脚本通过命令行接受目录路径并监视该目录,吐出出现在目录中的任何新图像文件的名称。 我想通过命令行添加第二个参数,该参数最终将馈入该函数,只要新图像文件出现在该目录中,该函数就会被调用。
from watchdog.events import PatternMatchingEventHandler
class MyHandler(PatternMatchingEventHandler):
patterns = ["*.jpg", "*.png", "*.tif"]
# we only care about newly created images
def on_created(self, event):
print(event.src_path + "want to have arg2 available here")
from watchdog.observers.polling import PollingObserver as Observer
if __name__ == '__main__':
args = sys.argv[1:]
observer = Observer()
observer.schedule(MyHandler(), path=args[0] if args else '/images')
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
这样,当我调用文件时,它可能是这样的:
python myfile.py /path/to/images arg2
和arg2将在on_created(self,event)中可用。
抱歉,这么新上课!
答案 0 :(得分:0)
您需要将额外的参数存储在MyHandler
的实例中,以便在调用on_event
方法时可以访问它们。像
class MyHandler(PatternMatchingEventHandler):
patterns = ["*.jpg", "*.png", "*.tif"]
def __init__(self, *args):
super().__init__()
self.extra_args = args
def on_created(self, event):
print(event.src_path + extra_args[0])
from watchdog.observers.polling import PollingObserver as Observer
if __name__ == '__main__':
args = sys.argv[1:]
observer = Observer()
observer.schedule(MyHandler(*args[1:]), path=args[0] if args else '/images')
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()