开发者

How to read a text from input file only after it is updated using python

Actually i will give input from my application1 to input.txt, which intern triggers {used pyinotify} program1 to run this program1 which updates output.txt file, but application1 which is reading from output.txt doesn't wait for program1 to complete the writing process on the text file(output.txt), It reads the old data from output.t开发者_JAVA百科xt. I need Application1 to wait for the completion of program1's process how can i do this??

import pyinotify,subprocess
def onChange(ev):
    cmd = ['/usr/bin/env', 'python','/var/www/cgi-bin/version2_1.py', ev.pathname]
    subprocess.Popen(cmd).communicate()
wm = pyinotify.WatchManager()
wm.add_watch('/var/www/cgi-bin/input.txt', pyinotify.IN_CLOSE_WRITE, onChange)
notifier = pyinotify.Notifier(wm)
notifier.loop()

This is the program that i have used to run my python program1 on the background on trigger to input text, right after this trigger the application1's execute this statement out_file=open("/var/www/cgi-bin/output.txt", "r").read()

Now application1 takes content of output before it's updated by program1!! I want Aplication1 to wait for the program1 to complete its run and updatition over output.txt

pls give me an idea how can i go about this..

Thank you :)


There are several ways to watch file changes in Python, most of them are platform-specific. Since you didn't specify your platform, here's a cross-platform package: http://packages.python.org/watchdog/

You should also take a look at the answers for this question: How do I watch a file for changes?

Edit

From the inotify FAQ:


Q: What is the difference between IN_MODIFY and IN_CLOSE_WRITE? The IN_MODIFY event is emitted on a file content change (e.g. via the write() syscall) while IN_CLOSE_WRITE occurs on closing the changed file. It means each change operation causes one IN_MODIFY event (it may occur many times during manipulations with an open file) whereas IN_CLOSE_WRITE is emitted only once (on closing the file).

Q: Is it better to use IN_MODIFY or IN_CLOSE_WRITE? It varies from case to case. Usually it is more suitable to use IN_CLOSE_WRITE because if emitted the all changes on the appropriate file are safely written inside the file. The IN_MODIFY event needn't mean that a file change is finished (data may remain in memory buffers in the application). On the other hand, many logs and similar files must be monitored using IN_MODIFY - in such cases where these files are permanently open and thus no IN_CLOSE_WRITE can be emitted.


Are you sure you're observing IN_CLOSE_WRITE? If you observe IN_MODIFY, then I won't be surprised if you get the event before the written data is flushed to the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜