473,388 Members | 1,220 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Putting a lock on file.

I have a file that a few different running scripts will need to access.
Most likely this won't be a problem but if it is, what do I need to do
to make sure scripts don't crash because the input file is in use?
Would it be best to run a loop like the following:

flag = 0
while not flag:
try:
open(file, 'r').read()
flag = 1
except:
pass

This may seem nice on paper but I hate to run a while for an
indeterminate amount of time. Is there anything else that can be done
that would be better?

Thanks,

Harlin Seritt

Sep 18 '05 #1
2 1277
Harlin Seritt wrote:
I have a file that a few different running scripts will need to access. [...] This may seem nice on paper but I hate to run a while for an
indeterminate amount of time. Is there anything else that can be done
that would be better?


On posix systems, there is a fcntl module [1] that can be useful.
[1] http://python.org/doc/2.4.1/lib/module-fcntl.html
Sep 18 '05 #2
On Sat, 17 Sep 2005 23:58:58 -0700, Harlin Seritt wrote:
I have a file that a few different running scripts will need to access.
Most likely this won't be a problem but if it is, what do I need to do
to make sure scripts don't crash because the input file is in use?
Would it be best to run a loop like the following:

flag = 0
while not flag:
try:
open(file, 'r').read()
flag = 1
except:
pass

This may seem nice on paper but I hate to run a while for an
indeterminate amount of time. Is there anything else that can be done
that would be better?


Instead of while flag, use a for loop. That way, when you have tried
unsuccessfully some known number of times, you can report back to the user
that you have tried and failed.

Also, in any serious program you should give better error reporting than
the above, especially for file-related errors. A bare "except:" that
catches all errors is generally bad practice. Eg, suppose you meant to
write "open(filename, 'r').read()" but accidentally mistyped ".raed()"
instead. Your except clause would catch the error, and you would spend
hours trying to work out why your file can't be opened.
Try something like this:
import errno

def get_file(fname, max_tries=10):
"""Returns the contents of fname, or None if there is an error."""
for i in range(max_tries):
try:
fp = open(fname, 'r')
text = fp.read()
fp.close() # don't wait for Python to close it for you
return text
except IOError, (error, message):
if error == errno.ENOENT:
print "No such file. Did you look behind the couch?"
break
elif error == errno.EIO:
print "I/O error -- bad media, no biscuit!"
break
elif error in (errno.EPERM, errno.EACCES):
print "Permission denied. Go to your room!"
break
elif error == errno.EINTR:
print "Interupted call... trying again."
continue
elif error in (errno.EWOULDBLOCK, errno.EAGAIN):
print "Temporary error..." \
" please wait a few seconds and try again."
continue
else:
# Some other error, just print Python's message.
print message
else:
# only called if you don't break
print "Sorry, the file is in use. Please try again later."
return None

You should look at the module errno, together with the function
os.strerror(), for more details. Of course, many people don't worry about
giving their own explanations for IOErrors, and simply return the same
error that Python does.
These two pages might be useful too:

http://www.gnu.org/software/libc/man...ror-Codes.html
http://www.gnu.org/software/libc/man...ile-Locks.html

--
Steven.
Sep 18 '05 #3

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

Similar topics

14
by: Antoon Pardon | last post by:
The queue and condition class allow threads to wait only a limited time. However this currently is implemented by a polling loop. Now for those who like to avoid polling I have here a Tlock...
0
by: John | last post by:
I've got multiple threads and processes that write to same file. Before writing all threads / processes first lock part of file and then write to file. If one thread / process locks file, another...
0
by: Andrew Dowding | last post by:
Hi Everybody, I have been looking at problems with my Windows Forms C# application and it's little Jet 4 (Access) database for the last few days. The Windows Forms app implements a facade and...
14
by: Gary Nelson | last post by:
Anyone have any idea why this code does not work? FileOpen(1, "c:\JUNK\MYTEST.TXT", OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.Shared) Dim X As Integer For X = 1 To 26 FilePut(1, Chr(X +...
4
by: muttu2244 | last post by:
hi all am trying to write some information into the file, which is located in ftp, and this file can be updated by number of people, but if at all i download a file from the ftp to my local...
4
by: visionstate | last post by:
Hi all, I have built my 1st database and it is ready to go on a shared network drive. I have read a few articles about the security in access but am having some trouble getting my head around it...
12
by: Elmo Mäntynen | last post by:
Is there something better than using fnctl? It seems a bit intimidating with a quick look.
5
by: pgdown | last post by:
Hi, I have several processes accessing files from one folder, but only one process should ever access each file. Once one process has the file, no other process should be allowed to access it,...
2
by: WingSiu | last post by:
I am writing a Logging util for my ASP.NET application. I am facing mulit process problem. I developed a class LogFactory, and have a method called Get_Logger to create a FileLogger, which will...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.