portalocker does not seem to lock
<p>I have a sort of checkpoint file which I wish to modify sometimes by various python programs. I load the file, try to lock it using portalocker, change it, than unlock and close it.</p>

<p>However, portalocker does not work in the simplest case.
I created a simple file:</p>

<pre><code>$echo "this is something here" &gt;&gt; test
$python
Python 3.5.2 (default, Jul  5 2016, 12:43:10) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; import portalocker
&gt;&gt;&gt; f = open("test",'w')
&gt;&gt;&gt; portalocker.lock(f, portalocker.LOCK_EX)
</code></pre>

<p>Meanwhile I can still open it in another terminal:</p>

<pre><code>$python
Python 3.5.2 (default, Jul  5 2016, 12:43:10) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; fl = open("test",'w')
&gt;&gt;&gt; fl.write("I can still overwrite this\n")
&gt;&gt;&gt; fl.close()
</code></pre>

<p>Then I close the first one, and check the file:</p>

<pre><code>&gt;&gt;&gt; portalocker.unlock(f)
&gt;&gt;&gt; f.close()
&gt;&gt;&gt; 
$ cat test
I can still overwrite this
</code></pre>

<p>What am I doing wrong?</p>

<p>The problem is that, by default, Linux uses advisory locks. <a href="https://stackoverflow.com/questions/12062466/mandatory-file-lock-on-linux">To enable mandatory locking (which you are referring to) the filesytem needs to be mounted with the <code>mand</code> option</a>. The advisory locking system actually has several advantages but can be confusing if you're not expecting it.</p>

<p>To make sure your code works properly in both cases I would suggest encapsulating both of the open calls with the locker.</p>

<p>For example, try this in 2 separate Python instances:</p>

<pre><code>import portalocker

with portalocker.Lock('test', truncate=None) as fh:
    fh.write('first instance')
    print('waiting for your input')
    raw_input()
</code></pre>

<p>Now from a second instance:</p>

<pre><code>import portalocker

with portalocker.Lock('test', truncate=None) as fh:
    fh.write('second instance')
</code></pre>

<p>Ps: I'm the maintainer of the portalocker package</p>

python python-3.x locking