Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a start on the win32 half of a portable implementation, that does not need a seperate locking mechanism.</p> <p>Requires the <a href="http://python.net/crew/mhammond/win32/" rel="nofollow noreferrer">Python for Windows Extensions</a> to get down to the win32 api, but that's pretty much mandatory for python on windows already, and can alternatively be done with <a href="http://www.python.org/doc/lib/module-ctypes.html" rel="nofollow noreferrer">ctypes</a>. The code could be adapted to expose more functionality if it's needed (such as allowing <code>FILE_SHARE_READ</code> rather than no sharing at all). See also the MSDN documentation for the <a href="http://msdn.microsoft.com/en-us/library/aa363858.aspx" rel="nofollow noreferrer"><code>CreateFile</code></a> and <a href="http://msdn.microsoft.com/en-us/library/aa365747.aspx" rel="nofollow noreferrer"><code>WriteFile</code></a> system calls, and the <a href="http://msdn.microsoft.com/en-us/library/aa363874.aspx" rel="nofollow noreferrer">article on Creating and Opening Files</a>.</p> <p>As has been mentioned, you can use the standard <a href="http://www.python.org/doc/lib/module-fcntl.html" rel="nofollow noreferrer">fcntl</a> module to implement the unix half of this, if required.</p> <pre><code>import winerror, pywintypes, win32file class LockError(StandardError): pass class WriteLockedFile(object): """ Using win32 api to achieve something similar to file(path, 'wb') Could be adapted to handle other modes as well. """ def __init__(self, path): try: self._handle = win32file.CreateFile( path, win32file.GENERIC_WRITE, 0, None, win32file.OPEN_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None) except pywintypes.error, e: if e[0] == winerror.ERROR_SHARING_VIOLATION: raise LockError(e[2]) raise def close(self): self._handle.close() def write(self, str): win32file.WriteFile(self._handle, str) </code></pre> <p>Here's how your example from above behaves:</p> <pre><code>&gt;&gt;&gt; path = "C:\\scr.txt" &gt;&gt;&gt; file1 = WriteLockedFile(path) &gt;&gt;&gt; file2 = WriteLockedFile(path) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockError: ... &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file1.close() &gt;&gt;&gt; print file(path).read() 111 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload