如何从Python调用Vim?

时间:2014-07-19 10:10:17

标签: python vim

我想要一个Python脚本来提示我输入一个字符串,但我想用Vim输入该字符串(因为字符串可能很长,我想在输入时使用Vim的编辑功能)

2 个答案:

答案 0 :(得分:4)

您可以使用您选择的文件路径调用vim:

from subprocess import call
call(["vim","hello.txt"])

现在您可以将此文件用作字符串:

file = open("hello.txt", "r")
aString = file.read()

答案 1 :(得分:3)

<强>解决方案:

#!/usr/bin/env python


from __future__ import print_function

from os import unlink
from tempfile import mkstemp
from subprocess import Popen


def callvim():
    fd, filename = mkstemp()

    p = Popen(["/usr/bin/vim", filename])
    p.wait()

    try:
        return open(filename, "r").read()
    finally:
        unlink(filename)


data = callvim()
print(data)

示例:

$ python foo.py 
This is a big string.

This is another line in the string.

Bye!