How to create a mapping to execute python code from Vim?
<p>Here's the steps I follow to execute python code from Vim:</p>

<ol>
<li>I write a python source code using Vim</li>
<li>I execute it via <code>:w !python</code></li>
</ol>

<p>and I'd like a shorter way to execute the code, so I searched the Internet for a shortcut key such as this map:</p>

<pre><code>autocmd FileType python nnoremap &lt;buffer&gt; &lt;F9&gt; :exec '!python' shellescape(@%, 1)&lt;cr&gt;
</code></pre>

<p>and added it to the <code>_vimrc</code> file. But when I hit <kbd>F9</kbd>, the following error message appears:</p>

<p><a href="https://i.stack.imgur.com/GTfPC.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/GTfPC.jpg" alt="enter image description here"></a></p>

<p>Here is the relevant text in the image above:</p>

<pre><code>python: can't open file ''D:/py2.py'': [Errno 22] Invalid argument
shell returned 2.
</code></pre>

<p>I have already searched the Internet, but I have not got any result.</p>

<p>I use gVim 8.0 in Windows 10, if that helps.</p>

<p>Interacting with command-line through vim, the much preferred way would be with exclamation.<br>Instead of:</p>

<pre><code>:exec '!python' shellescape(@%, 1)&lt;cr&gt;
</code></pre>

<p>Try doing the easy way:</p>

<pre><code>:update&lt;bar&gt;!python %&lt;CR&gt;
</code></pre>

<p>here in the above code:<br>
<code>update</code> helps save file if modified (<em>preferred</em>) or can also use <code>w</code>.<br>
<code>&lt;bar&gt;</code> will pipe the commands properly.<br>
<code>!python %</code> will run the file as <code>python filename</code>.<br></p>

<p>So basically, put this in your <code>.vimrc</code> file, and that'll do it:</p>

<pre><code>autocmd FileType python nnoremap &lt;buffer&gt; &lt;F9&gt; :update&lt;bar&gt;!python %&lt;CR&gt;
</code></pre>

python vim compilation shortcut