Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python code in Vim without saving

Tags:

python

vim

Is there a way to run my current python code in vim without making any changes to the file? Normally, when I want to test my code from within vim, I would execute this:

:w !python

However, this overrides the current file I am editing. Often, I add print statements or comment stuff out to see why my code isn't working. I do not want such changes to overwrite a previous version of whatever .py file I'm currently working on. Is there a way to do so? Perhaps a combination of saving to a temporary file and deleting it afterwards?

like image 937
Wet Feet Avatar asked Apr 10 '18 16:04

Wet Feet


2 Answers

You have already answered your own question:

:w !python

will run the file in python without saving it. Seriously, test it out yourself! make some changes, run :w !python and then after it runs, run :e!. It will revert all of your changes.

The reason this works is because :w does not mean save. It means write, and by default, it chooses to write the file to the currently selected file, which is equivalent to saving. In bash speak, it's like

cat myfile > myfile

But if you give an argument, it will write the file to that stream rather than saving. In this case, your writing it to python, so the file is not saved.


I wrote a much longer answer on this topic here.

like image 84
DJMcMayhem Avatar answered Sep 25 '22 13:09

DJMcMayhem


You seem to be confusing :w[!] filename and :w !command.

The former writes the buffer to file filename whereas the latter passes the content of the buffer to command command.

The former could eventually lead to data loss but the latter can't (as long as you don't do crazy things incommand).

enter image description here

like image 36
romainl Avatar answered Sep 22 '22 13:09

romainl