How to run Vim shell from script's path?
Search results returned tones of Q&As and I don't know how to rephrase this better, so pardon me if it's a duplicate:
I'm running a python script with Vim. The script is at ~/path/to/my/script.py
and there is a style sheet file in the same path.
The code's content opens the file:
f = open('./stylesheet.css', 'r')
s = f.read()
f.close()
And if I r开发者_JS百科un my code from Vim like so :!python %
,it will return: IOError: [Errno 2] No such file or directory: 'stylesheet.css'
So it seems Vim runs my code not from the code's location, but from /home or root?
How can I make it use the code's path as the root path during execution?
You can use this :lcd %:p:h | !python %
.
A brief explanation. lcd changes directory to the current file being edited - http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file
Then executes the python command on the file.
The one problem with this command is that your current directory will now be (from your example) ~/path/to/my/
. You will have to do another :lcd
to get back to your current directory. I wasn't able to find a way to combine all of it into one command in vim. Maybe someone else can.
Edit - How-to cd back again
(removed my complex method)
for the simple solution refer to ib's comments below.
To open a file in the same directory as your script, try something like:
import os
script_dir = os.path.dirname(__file__)
target_file = os.path.join(script_dir, 'stylesheet.css')
with open(target_file, 'r') as f:
s = f.read()
The shortcut in vim for the current file is %, so instead of :!python $
, type :!python %
精彩评论