Git在个人项目中提交Vim

时间:2018-01-26 12:06:53

标签: python vim scripting

我正在创建一个小的python脚本,它应该提示用户输入。我喜欢git commit如何通过vim提示提示用户,然后使用此提示获取提交消息。

是否可以在python中实现此行为?

我不能使用输入(或一般的stdin)

1 个答案:

答案 0 :(得分:1)

非常简单:将初始文本放入临时文件,启动编辑器(由知名环境变量确定并回退到vi),等待编辑器完成并获取临时文件的内容。

请参阅https://chase-seibert.github.io/blog/2012/10/31/python-fork-exec-vim-raw-input.html

上的示例
import tempfile
import subprocess
import os

def raw_input_editor(default=None, editor=None):
    ''' like the built-in raw_input(), except that it uses a visual
    text editor for ease of editing. Unline raw_input() it can also
    take a default value. '''
    with tempfile.NamedTemporaryFile(mode='r+') as tmpfile:
        if default:
            tmpfile.write(default)
            tmpfile.flush()
        subprocess.check_call([editor or get_editor(), tmpfile.name])
        tmpfile.seek(0)
        return tmpfile.read().strip()

def get_editor():
    return (os.environ.get('VISUAL')
        or os.environ.get('EDITOR')
        or 'vi')