473,811 Members | 2,756 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1301
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(filen ame, '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.EWOULDBL OCK, 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
2813
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 class that allows for a timeout but doesn't use polling. All comments are welcome. ----------------------- Tlock.py -------------------------------
0
4552
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 threads / processes can not lock this file again. And I want that all threads / processes wait until first thread frees lock by calling FileStream.Unlock. But I do not know what code should I use that all threads / processes wait until first...
0
3173
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 implementation, data abstraction layer. But because each data adapter in the implementation layer has a connection object that opens and closes as needed, I found I got several errors from the Jet engine when there were simultaneous connections to...
14
3840
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 + 64)) Next Lock(1, 5, 10)
4
2265
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 machine, update it and then upload it back to ftp, and at the same time if some one else downloads the same file for the modification, then the data will be overwritten. so is there a way in Python script where i can lock the file, so that no one...
4
1984
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 all. Firstly, do I need to convert my database from an MDB file to an MDE file? Basically, what i want is for all users to be able to search through the database but only let myself edit the database. I changed some options in the 'Startup'...
12
5455
by: Elmo Mäntynen | last post by:
Is there something better than using fnctl? It seems a bit intimidating with a quick look.
5
4098
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, even after the first process is finished with it, except in the case where the first process crashes. In pseudo code.. * Open file with exclusive lock * Process file - failure will throw exception, skipping 'Remove
2
2627
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 write text into a text file. // sample code FileLogger logger = LogFactory.Get_Logger(); logger.Log("Message here");
0
9727
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
10647
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
10386
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...
1
10398
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10133
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
6889
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4339
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
3865
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3017
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.