Reman
Reman

Reputation: 8119

How to use a vim list in a python command?

My vim list:

  let ListRange = []  
  let ListRange = ['2','3','hello']   

I want to import the list in a python command:

exe "r!python -c \"import random ; print('\\n'.join(format(random.choice(ListRange)) for i in range(14)))\""

This gives an error:
Traceback (most recent call last):
File "", line 1, in
File "", line 1, in
NameError: global name 'listrange' is not defined

How can I use the vim list in above python command?

I know that it is possible to declare the list within the python command self, but I want to declare it from within vim environment.

Upvotes: 1

Views: 244

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172698

With :execute, you need to carefully distinguish between the quoted parts, which are evaluated by Python, and the unquoted parts, which are Vim expressions. Your mistake is that ListRange is a Vim variable, but you've included it in the quoted Python part.

To fix this, split the string into two parts, and insert the ListRange literally and unquoted, using Vim's string() to generate a text representation of the list:

exe "r!python -c \"import random ; print('\\n'.join(format(random.choice(" . string(ListRange) . ")) for i in range(14)))\""

You're lucky here that Vim's and Python's List formats are very similar; it only works because of this (for this particular input; more complex List contents may cause failures).

Upvotes: 1

Related Questions