473,805 Members | 2,168 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

wait until change

Tom
Hi,

I have the following problem. I analyse data from a file. When I am done
analysing all the data that was in that file, I want to let my program
wait until this specific file has changed (which indicates that new data
has been added to the file from a third party program that I don't
control). If that file has changed, I want my program to continue.

What would be the appropriate command to check if the file changed? And
how can I implement "wait until" into my program? I googled a lot to
find any hints, but couldn't find anything helpful. But I found
something about a python that was stabbed in NY in 2000. :-) Thought
that was funny. :-)

I would deeply appreciate, if you could maybe include some little
fragments of code to show me how to use your suggestions. I am
relatively new to python and I often have problems with Pythons Library
Reference, because it doesn't show examples and is very technically.
That makes it difficult for me to really understand that. It also would
be great, if you could tell me which modules I have to include. I hope
all that is not asked too much. I assume that both problems can be
solved with a few easy lines of code. I just don't know them. :-)

Thanks a lot for your help and suggestions.
Regards Tom

Jul 18 '05
19 9452
I just took a midterm in my operating systems class, and a big topic was
"busy waiting" and semaphores.

And now, today, a real-world example! Anyway, the time.sleep() method
is probably good enough, but how would a semaphore solution work in
python? A semaphore solution is one where the process that uses the
updated file is asleep until another process says "Hey! Wake up! I
updated the file!". This avoids all those check_for_updat e() calls
which bog down the CPU.

Anyone?
Jul 18 '05 #11
Matthew Wilson wrote:

I just took a midterm in my operating systems class, and a big topic was
"busy waiting" and semaphores.

And now, today, a real-world example! Anyway, the time.sleep() method
is probably good enough, but how would a semaphore solution work in
python? A semaphore solution is one where the process that uses the
updated file is asleep until another process says "Hey! Wake up! I
updated the file!". This avoids all those check_for_updat e() calls
which bog down the CPU.


In this case, it appears the OP doesn't have the capability of changing
the other application, so what you suggest is out.

Dave's example with WMI uses the *operating system* to essentially
signal semaphore-like that an update has been made. As I suggested,
it's obviously much more complicated than the simple time.sleep()
plus os.stat() approach, but there are times when it's the right
way to approach this problem.

-Peter
Jul 18 '05 #12
Peter Hansen <pe***@engcorp. com> writes:
Matthew Wilson wrote:

I just took a midterm in my operating systems class, and a big topic was
"busy waiting" and semaphores.

And now, today, a real-world example! Anyway, the time.sleep() method
is probably good enough, but how would a semaphore solution work in
python? A semaphore solution is one where the process that uses the
updated file is asleep until another process says "Hey! Wake up! I
updated the file!". This avoids all those check_for_updat e() calls
which bog down the CPU.
In this case, it appears the OP doesn't have the capability of changing
the other application, so what you suggest is out.

Dave's example with WMI uses the *operating system* to essentially
signal semaphore-like that an update has been made. As I suggested,
it's obviously much more complicated than the simple time.sleep()
plus os.stat() approach, but there are times when it's the right
way to approach this problem.


Just for completeness, it should be mentioned that the win32 api
functions FindFirstChange Notification and FindNextChangeN otification
could also be used. They are wrapped in win32all, and probably could
also be made to work with ctypes. Platform dependend, sure, but maybe a
much more lightweight approach than using wmi (and, for me at least,
probably better understandable) .
-Peter


Thomas
Jul 18 '05 #13
Thomas Heller wrote:
Just for completeness, it should be mentioned that the win32 api
functions FindFirstChange Notification and FindNextChangeN otification
could also be used. They are wrapped in win32all, and probably could
also be made to work with ctypes. Platform dependend, sure, but maybe a
much more lightweight approach than using wmi (and, for me at least,
probably better understandable) .


And to be *really* complete, Windows NT/2000/XP has the
ReadDirectoryCh angesW function, which has some improvements over the
Find...ChangeNo tification functions. Not available on Win95/98/Me, though.

-Mike
Jul 18 '05 #14
Michael Geary wrote:
And to be *really* complete, Windows NT/2000/XP has the
ReadDirectoryC hangesW function, which has some improvements over the
Find...ChangeN otification functions. Not available on Win95/98/Me, though.

-Mike


And to be really, really complete, Unix (in my case Linux, afaik also
works under Solaris and HP-UX) has FAM (the file alteration monitor),
which works as a user-space daemon to which a program can attach to get
a file/directory change notification. The daemon itself uses a special
kernel module to get these notification right from the VFS (virtual file
system).

I recall that there was a Python-wrapper somewhere for the fam client
library.

HTH!

Heiko.
Jul 18 '05 #15
In article <bm**********@n ews.uni-kl.de>, Tom <ll************ @gmx.net> wrote:

I have the following problem. I analyse data from a file. When I am done
analysing all the data that was in that file, I want to let my program
wait until this specific file has changed (which indicates that new data
has been added to the file from a third party program that I don't
control). If that file has changed, I want my program to continue.

What would be the appropriate command to check if the file changed? And
how can I implement "wait until" into my program? I googled a lot to
find any hints, but couldn't find anything helpful. But I found
something about a python that was stabbed in NY in 2000. :-) Thought
that was funny. :-)


os.stat() is the correct answer, but I question the other responses that
suggest using time.sleep(). Unless your application stores a lot of
data in memory, you might be better off using your OS to periodically
run your application; your application stores the result of os.stat() in
a private file. On Unix-like systems, the facility is called cron;
dunno what that would be on Windows. This would simplify your program;
it also means your program would automatically start when the system
gets rebooted.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
Jul 18 '05 #16
Aahz wrote:
In article <bm**********@n ews.uni-kl.de>, Tom <ll************ @gmx.net> wrote:
I have the following problem. I analyse data from a file. When I am done
analysing all the data that was in that file, I want to let my program
wait until this specific file has changed (which indicates that new data
has been added to the file from a third party program that I don't
control). If that file has changed, I want my program to continue.

What would be the appropriate command to check if the file changed? And
how can I implement "wait until" into my program? I googled a lot to
find any hints, but couldn't find anything helpful. But I found
something about a python that was stabbed in NY in 2000. :-) Thought
that was funny. :-)

os.stat() is the correct answer, but I question the other responses that
suggest using time.sleep(). Unless your application stores a lot of
data in memory, you might be better off using your OS to periodically
run your application; your application stores the result of os.stat() in
a private file. On Unix-like systems, the facility is called cron;
dunno what that would be on Windows. This would simplify your program;
it also means your program would automatically start when the system
gets rebooted.


i'm currently running a python script that automatically runs when the system gets rebooted on windows. i use the
"scheduled tasks" control panel applet. you can have your program scheduled to run weekly, monthly, daily, once, at
system startup, at logon, or when idle. you can specify start/end times, durations, how to repeat the task, plus a
bunch more options.

bryan

Jul 18 '05 #17
On Sat, 18 Oct 2003 03:29:33 +0200, Heiko Wundram wrote:
Michael Geary wrote:
And to be *really* complete, Windows NT/2000/XP has the
ReadDirectory ChangesW function, which has some improvements over the
Find...Change Notification functions. Not available on Win95/98/Me, though.

-Mike


And to be really, really complete, Unix (in my case Linux, afaik also
works under Solaris and HP-UX) has FAM (the file alteration monitor),
which works as a user-space daemon to which a program can attach to get
a file/directory change notification. The daemon itself uses a special
kernel module to get these notification right from the VFS (virtual file
system).

I recall that there was a Python-wrapper somewhere for the fam client
library.


There also appears to be a python wrapper for dnotify which is the
kernel-level file-change notification system so that you don't have to
have famd and portmap running just to get file notifications.. . It appears
to be apart of twisted according to this message:
http://twistedmatrix.com/pipermail/t...il/003873.html

-Mark
Jul 18 '05 #18
If you dont want to use sleep(), try this mechanism
based on 'Timer' class in the threading module.

1. Create a timer thread that calls a function
which checks for the time stamp using os.stat().
2. Schedule the timer to wake up after 'n' seconds
and call this function.
3. If the call succeeds all and well, otherwise in
the function, create a new timer and set it again
to wake itself up after another 'n' seconds.

A timer can be used only once so you need to make a new timer
for every wake-up call. Perhaps not very good on memory,
but it might save you the CPU cycles.

You can wrap the whole thing in a class with the timer
bound to a local class variable, and the function as
another class attribute.

HTH.

-Anand

Tom <ll************ @gmx.net> wrote in message news:<bm******* ***@news.uni-kl.de>...
Lane LiaBraaten wrote:
I would use os.stat() which returns all sorts of info about the file including
modification time.

More info at: http://web.pydoc.org/1.5.2/os.html

time=os.stat(f ile)[8]

# analyze data

while 1:
if os.stat(file)[8]>time:
#analyze data again

Hi Lane,

thanks for your answer it works great and gives me a lot of new ideas
that I can work with.
That "while 1" command looks interessting. I never used while that way.
The Library Reference doesn't explain it. But am I right if I assume
that this is a loop that continues forever? Despite using break of
course. I ask, because your suggestion works, but unfortunately uses
100% of my CPU power. :-( Well, it works, but is there maybe another way
to do the same without using so much of my resources? :-) That would be
great.

Thank's again.
Tom

Jul 18 '05 #19
I thought this was fairly straightforward , but when
I tried to write one I figured out that the standard
python Timers cannot be used.

Anyway here is how you would go about doing it.
This piece of code uses a time out as an exit condition,
whereas in the scenario given by the O.P it would be
the file's timestamp verification.

----------------------------------------------------
from threading import Thread
import time

class ModifiedTimer(T hread):
""" Modified timer with a maximum timeout
and repeated calls """

def __init__(self, interval, maxtime, target):
self.__interval = interval
self.__maxtime = maxtime
self.__tottime = 0.0
self.__target = target
self.__flag = 0
Thread.__init__ (self, None, 'mytimer', None)

def run(self):

while self.__flag==0:
time.sleep(self .__interval)
self.__target()
self.__tottime += self.__interval

if self.__tottime >= self.__maxtime:
print 'Timing out...'
self.end()

def end(self):
self.__flag=1

class MyTimer:

def __init__(self):
self.__interval = 5.0

def __timerfunc(sel f):
print 'Hello, this is the timer function!'

def make_timer(self , interval):
self.__interval = interval
self.__timer = ModifiedTimer(s elf.__interval, 60.0, self.__timerfun c)
self.__timer.st art()

if __name__=="__ma in__":
t=MyTimer()
t.make_timer(10 .0)

----------------------------------------------------------------

The code works as expected. I tested on Windows 98
using python 2.3.

-Anand Pillai


py*******@Hotpo p.com (Anand Pillai) wrote in message news:<84******* *************** ****@posting.go ogle.com>...
If you dont want to use sleep(), try this mechanism
based on 'Timer' class in the threading module.

1. Create a timer thread that calls a function
which checks for the time stamp using os.stat().
2. Schedule the timer to wake up after 'n' seconds
and call this function.
3. If the call succeeds all and well, otherwise in
the function, create a new timer and set it again
to wake itself up after another 'n' seconds.

A timer can be used only once so you need to make a new timer
for every wake-up call. Perhaps not very good on memory,
but it might save you the CPU cycles.

You can wrap the whole thing in a class with the timer
bound to a local class variable, and the function as
another class attribute.

HTH.

-Anand

Tom <ll************ @gmx.net> wrote in message news:<bm******* ***@news.uni-kl.de>...
Lane LiaBraaten wrote:
I would use os.stat() which returns all sorts of info about the file including
modification time.

More info at: http://web.pydoc.org/1.5.2/os.html

time=os.stat(f ile)[8]

# analyze data

while 1:
if os.stat(file)[8]>time:
#analyze data again

Hi Lane,

thanks for your answer it works great and gives me a lot of new ideas
that I can work with.
That "while 1" command looks interessting. I never used while that way.
The Library Reference doesn't explain it. But am I right if I assume
that this is a loop that continues forever? Despite using break of
course. I ask, because your suggestion works, but unfortunately uses
100% of my CPU power. :-( Well, it works, but is there maybe another way
to do the same without using so much of my resources? :-) That would be
great.

Thank's again.
Tom

Jul 18 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3579
by: Jeronimo Bertran | last post by:
I have a multithreaded application that manipulates a Queue: protected Queue outputQueue; when I add elements to the queue I use a critical section private void Add(OutputRecord record) { lock(outputQueue) {
22
2572
by: codefixer | last post by:
Hi, I have a situation where I have to handle the following scenario. The main() must wait for child to complete or the main() must kill the child after 3 seconds and exit. /* Assume everythign is declared */ time(&start); while ( childpid != wait(&status) )
6
5714
by: Jeremy Chapman | last post by:
I have a button on my page which when clicked redirects to another page. on the page load of the page that I've redirected to, there is a long query. What I want to do is with dhtml, display test in the center of the screen saying 'please wait..' so that the text displays until the new page is returned. My problem is that the html is not visually updated because the browser is busy waiting for the http request to complete. Is there any...
11
6975
by: ryan | last post by:
Hi, I've omitted a large chunk of the code for clarity but the loop below is how I'm calling a delegate function asynchronously. After I start the each call I'm incrementing a counter and then making the main thread sleep until the counter gets back to zero. The call back function for each call decrements the counter. Is there a better way to make the thread wait until all calls are complete besides using the counter? I've seen some things...
18
51027
by: Coder | last post by:
Howdy everybody! How do I do the following... while (myVary != true){}; Obviously I do not want to use 100% of the processor to stay in this infinite loop till myVar == true. But wait do I do? Thanks yal!
8
37737
by: C.Joseph Drayton | last post by:
Hi All, I am calling a PHP script that does an operation then sends back a result. I want JavaScript to wait until that result has been recieved. I am using the following code. What can I do to stop it from generating a 'Too much recursion' error? function WaitForData() {
12
5278
by: Perecli Manole | last post by:
I am having some strange thread synchronization problems that require me to better understand the intricacies of Monitor.Wait/Pulse. I have 3 threads. Thread 1 does a Monitor.Wait in a SyncLock block protecting a resource. Thread 2 and 3 also have a SyncLock block protecting the same resource and after executing some code in their blocks they both do a Monitor.Pulse to hand of the locked resource back to thread 1. While thread 1 has...
1
5692
by: peterggmss | last post by:
This is a slot machine game, 2 forms. One is the actual game (frmMachine) and the other is in the background and randomizes the images shown on frmMachine. I need to make frmMachine wait for frmRandom, i tried it with the Sleep API and a Do/Until Loop and neither worked, could you please help me, I have my code below. frmMachine 'Slot Machine, (c) 2006 Peter Browne, GPL Licensed ' 'Peter Browne 'Sheridan Corporate Centre '2155 Leanne...
2
3491
by: greyradio | last post by:
I've recently have been given an assignment to do and it seems that notify() does notify() any of the waiting threads. The project entails 10 commuters and two different toll booths. The EZPass booth allows a commuter to pass easily while a cash booth creates a wait line. The wait line is expected to wait for the 5th commuter to pass before any commuter on the wait line can pass through the toll booth. This is where my problem lies. All the...
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10613
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10107
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.