1

How would I do something like the following in vim:

echom "hello"
pyx print('New item')
let a = (pyx import socket; socket.gethostname())
echom a

The first and second lines work; but how to assign a variable name to a python value/output?

2 Answers 2

1

Import module vim and execute vim's command let passing value from Python:

:py3 import socket, vim; hn=socket.gethostname(); vim.command('let vim_hn="'+hn+ '"')

hn=… assigns a variable in Python; 'let vim_hn="'+hn+ '"' passes its value to command let; something like let vim_hn="myhost"; vim.command() executes that let from Python.

Now you can inspect the value in vim:

:echo vim_hn
Sign up to request clarification or add additional context in comments.

4 Comments

no module named vim -- does this require an additional library to play nice with vim in python?
actually not bad at all. I simplified it to: py3 import socket; vim.command("let vim_hn='%s'" % socket.gethostname()) echom "The hostname is: " . vim_hn
@David542 Never saw this. Any chance you run the command in an external Python? Module vim is only available in built-in Python, of course.
yea, exactly. And it's auto-imported, so that import statement isn't even required. Actually I was surprised how simple it was to use python here.
1

I've experimented a few approaches

  • I prefer :let vimvar = pyxeval('PythonExpression') from vim code when possible
  • Sometimes vim.command('let vimvar = ...') makes more sense, in particular from Python code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.