[英]Python Watchdog get the name of the file that was just created?
I have written a script that observes a directory for creation of new files.我编写了一个脚本来观察用于创建新文件的目录。 I set up a split function to split the event.src_path from the target directory that i was giving the observer.
我设置了一个拆分 function 以将 event.src_path 从我提供给观察者的目标目录中拆分出来。 This allowed me to get the file_name successfully.
这使我能够成功获取 file_name。
See script below请参阅下面的脚本
def on_created(event):
source_path = event.src_path
file_name = source_path.split(TargetDir,1)[1]
print(f"{file_name} was just Created")
if __name__ == "__main__":
for dir in range(len(TargetDir)):
event_handler = FileSystemEventHandler()
event_handler.on_created = on_created
observer = Observer()
observer.schedule(event_handler, path = TargetDir[0], recursive=True)
observer.start()
However, now i am trying to feed in a list of Target directories and am looping through each one and calling the on_created() method.但是,现在我正在尝试输入一个目标目录列表,并循环遍历每个目录并调用 on_created() 方法。 Now obviously the Target directory is no longer a global variable, and i need to try to pass each Dir in to the function. Im using watchdog, and don't think it's possible to add extra arguments to the on_created() function. If i'm wrong, please let me know how to do this?
现在显然 Target 目录不再是全局变量,我需要尝试将每个 Dir 传递给 function。我正在使用看门狗,并且认为不可能向 on_created() function 添加额外的 arguments。如果我错了,请告诉我该怎么做? otherwise, is there no simpler way to just get the name of the file that was created, without passing in the target directory just for that reason?
否则,是否没有更简单的方法来获取创建的文件的名称,而无需为此传递目标目录? I can get the event.src, however this gives the full path, and then i wouldn't know where to split it, if it were scanning multiple directories.
我可以获得 event.src,但是这给出了完整路径,然后如果它正在扫描多个目录,我就不知道在哪里拆分它。
Well one simple way is to pass in a different function for each directory, for example:好吧,一种简单的方法是为每个目录传入不同的 function,例如:
def create_callback(dir):
def on_create(event):
source_path = event.src_path
file_name = source_path.split(dir, 1)[1]
print(f"{file_name} was just Created")
return on_create
if __name__ == "__main__":
for dir in range(len(TargetDir)):
event_handler = FileSystemEventHandler()
event_handler.on_created = create_callback(dir)
observer = Observer()
observer.schedule(event_handler, path=TargetDir[0], recursive=True)
observer.start()
The dir
variable is attached to the scope of the on_create
function and can therefore be used from within the function. dir
变量附加到 on_create function 的on_create
,因此可以在 function 中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.