我想編寫一個python腳本(並在後臺在Windows 7上24/7全天候運行),它檢查是否在c:\數據\或c:\ Data子目錄(例如c:\ Data \ 1 \ 2 \ 3 \或c:\ Data \ 1 \ test \ 2)python:如何跟蹤子目錄中的目錄中的新目錄創建
什麼是最高性能的方式(在Windows 7上)跟蹤目錄創建?
我想編寫一個python腳本(並在後臺在Windows 7上24/7全天候運行),它檢查是否在c:\數據\或c:\ Data子目錄(例如c:\ Data \ 1 \ 2 \ 3 \或c:\ Data \ 1 \ test \ 2)python:如何跟蹤子目錄中的目錄中的新目錄創建
什麼是最高性能的方式(在Windows 7上)跟蹤目錄創建?
使用pywin32掛接到windows api。然後使用change notifications之一在發生變化時進行更改。這在python中會很痛苦,但它是監視目錄更改的最高性能方式。請注意,這隻適用於本地文件系統,而不適用於網絡文件系統。
你唯一的選擇是檢查和睡眠,這是充滿樂趣的小驚喜和邊緣情況。我最喜歡的是windows在寫入文件內容之前寫入文件指針。如果有足夠的時間,你會在文件存在之前「查找」一個文件,並且你的所有代碼都會失敗。在你看到它後,你不能等待一段固定的時間,因爲它可能沒有寫完。
網絡寫入數百個meg文件的任何人?
聽起來像最好也是最難的方式 – Johnny
@JohnBrown我寫了一個python程序,通過網絡共享監視目錄,所以我不能使用更改通知。經驗表明,我告訴你是否儘可能不要使用睡眠。 –
下面是一個簡單的掃描工具,掃描的變化每10秒:
>>> import os
>>> from time import sleep
>>> def build_dir_tree(base):
all_dirs = []
for root, dirs, files in os.walk(base):
for dir_ in dirs:
all_dirs.append(os.path.join(root, dir_))
return all_dirs
>>> base = r'E:\CFM\IT\Dev\Python\test'
>>> old_dirs = build_dir_tree(base)
>>> while True:
new_dirs = build_dir_tree(base)
removed = [d for d in old_dirs if d not in new_dirs]
added = [d for d in new_dirs if d not in old_dirs]
print 'Added :', added, '- Removed:', removed
old_dirs = new_dirs
sleep(10)
Added : [] - Removed: []
Added : ['E:\\CFM\\IT\\Dev\\Python\\test\\hep'] - Removed: []
Added : [] - Removed: []
Added : ['E:\\CFM\\IT\\Dev\\Python\\test\\hop\\hap'] - Removed: []
Added : [] - Removed: ['E:\\CFM\\IT\\Dev\\Python\\test\\hep']
你必須與你的時間步長來適應它,時間顯示等
不幸的是這很慢。如果可以儘可能快地跟蹤目錄創建,這將是很酷的,例如,通過使用某種窗口通知 – Johnny
一些谷歌搜索讓我這個:http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html – forivall
已解決。謝謝forivall! 「ReadDirectoryChanges」示例就是我需要的! – Johnny