3

I use YouCompleteMe for python3 code completion, and when I have

let g:ycm_python_binary_path = '/usr/bin/python3'

in my ~/.vimrc it works great. However, if I change it to

let python3path = system('/usr/bin/which python3')
let g:ycm_python_binary_path = python3path

It stops working. In both cases after vim startup the :echo g:ycm_python_binary_path shows /usr/bin/python3

What am I doing wrong?

3

Almost all Unix commandline programs end their output with a trailing newline, and Vim's system() doesn't remove this.

This can be a difficult to spot with a regular :echo; the easiest way to check this from Vim is by piping the output to hexdump:

:echo system('/usr/bin/which python3 | hexdump -C')
00000000  2f 75 73 72 2f 62 69 6e  2f 70 79 74 68 6f 6e 33  |/usr/bin/python3|
00000010  0a                                                |.|
00000011

The last character (0a) is a newline ("\n").

There is no straight-forward way to dump the hex output of a Vim string like with hexdump; so if you want to check the value of a string then the easiest way is to output with a prefix and suffix; for example:

:let python3path = system('/usr/bin/which python3')
:echo 'X' . python3path . 'X'
X/usr/bin/python3
X

Notice how that second X is on a new line?

You can use something like this to remove the newline python3path:

:let python3path = system('/usr/bin/which python3')[:-2]
:echo 'X' . python3path . 'X'
X/usr/bin/python3X

which removes the last character (the \n) from the string that system() returns.

you could substitute() it, which is guaranteed to work for strings that don't end with a \n at a (very) slight performance/readability cost:

:let python3path = substitute(system('/usr/bin/which python3'), "\n$", "", 0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.