我想知道是否有辦法等待文件被更新,然後一旦更新就從中讀取。所以如果我有file.txt
,我想等到有新的東西寫入它,然後讀取它/處理它/ etc。目前我輪詢使用Time::HiRes::sleep(.01)
,但我想知道是否有更好的方法。謝謝。什麼是等待文件更新並在Perl中讀取的好方法?
5
A
回答
9
是的,還有更好的方法。在Windows上,您可以使用FileSystemWatcher界面,在Linux上使用inotify。
的Windows
use Win32::FileSystem::Watcher;
my $watcher = Win32::FileSystem::Watcher->new("c:\\");
# or
my $watcher = Win32::FileSystem::Watcher->new(
"c:\\",
notify_filter => FILE_NOTIFY_ALL,
watch_sub_tree => 1,
);
$watcher->start();
print "Monitoring started.";
sleep(5);
# Get a list of changes since start().
my @entries = $watcher->get_results();
# Get a list of changes since the last get_results()
@entries = $watcher->get_results();
# ... repeat as needed ...
$watcher->stop(); # or undef $watcher
foreach my $entry (@entries) {
print $entry->action_name . " " . $entry->file_name . "\n";
}
# Restart monitoring
# $watcher->start();
# ...
# $watcher->stop();
LINUX
use Linux::Inotify2;
my $inotify = new Linux::Inotify2();
foreach (@ARGV)
{
$inotify->watch($_, IN_ALL_EVENTS);
}
while (1)
{
# By default this will block until something is read
my @events = $inotify->read();
if (scalar(@events)==0)
{
print "read error: $!";
last;
}
foreach (@events)
{
printf "File: %s; Mask: %d\n", $_->fullname, $_->mask;
}
}
2
File::Tail將輪詢文件,但在你的方法有幾個優點:
- 投票表決時間重新計算動態地基於數字自上次輪詢後寫入的行數
- 如果文件保持不變,輪詢將會減慢以避免使用CPU
- File :: Tail將檢測文件是否被截斷,移動和/或重新創建,爲你打開文件
- 它可以綁定一個普通的文件句柄,你可以像普通文件一樣使用,不需要任何特殊的API或語法。從的perldoc
實施例:
use File::Tail;
my $ref=tie *FH,"File::Tail",(name=>$name);
while (<FH>) {
print "$_";
}
相關問題
- 1. C++什麼是從文本文件讀取的好方法?
- 2. 如何讓mod_python等待更新的文本文件讀取?
- 3. 在svn中重命名文件的更好方法是什麼?
- 4. 最好的方法等待在Java中
- 5. 在Delphi中讀取大文件的最快方法是什麼?
- 6. 在PHP中讀取大文件的最佳方法是什麼?
- 7. 有沒有什麼方法可以在Perl中讀取MATLAB的.mat文件?
- 8. 在Perl中打開和讀取文件的最佳方式是什麼?
- 9. 什麼是複製文本文件的更好方法?
- 10. 獲取上下文的更好方法是什麼?
- 11. Java中更好的等待語法
- 12. 在Haskell中等待並檢測按鍵的簡單方法是什麼?
- 13. 在TestCafe中等待'WebComponentsReady'事件的最佳方式是什麼?
- 14. 這是從文本文件中讀取的好方法嗎?
- 15. 什麼是等待?
- 16. 等待在ActiveMQ中接收異步消息的更好方法
- 17. 更好的方法來讀取/寫入Python中的文件?
- 18. 用Java讀取文件的好方法
- 19. 有什麼更好的方法來讀取字符?
- 20. 從Excel文件中讀取數據的更好方法
- 21. 爲什麼要在方法中間等待異步方法?
- 22. 什麼是更好的方法?
- 23. 什麼是更好的方法?
- 24. 什麼是更好的方法
- 25. 從url保存(xml)文件的更好方法是什麼?
- 26. 寫更新查詢的更好方法是什麼?
- 27. 如何在Perl中讀取持續更新的日誌文件?
- 28. C#中的BinaryFormatter是讀取文件的好方法嗎?
- 29. 什麼是獲取文件大小的好方法?
- 30. 調用異步方法,然後等待它,有什麼好處?
http://search.cpan.org/perldoc?SGI::FAM和http://search.cpan.org/perldoc?Sys::Gamin可能適用於文件系統和unotify不支持的UNIX。 – ephemient 2010-03-02 22:50:22