【问题标题】:Git commit Vim in personal project个人项目中的 Git 提交 Vim
【发布时间】:2018-01-26 12:06:52
【问题描述】:

我正在制作一个小 Python 脚本,它会提示用户输入。我喜欢git commit 使用 vim 提示符提示用户,然后使用此提示符获取提交消息的方式。

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

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

【问题讨论】:

  • 如果您不能使用标准输入,那么您启动的任何程序都可以使用它吗?有效地,当您使用子进程时,您可以将标准输入转发到子进程的标准输入,这使其具有交互性。 IIRC git 的作用是告诉 vim 使用某个临时文件的保存文件名打开,然后在 vim 退出后读取该文件。看看stackoverflow.com/questions/40935208/…
  • 你可以在这里看到 git 是如何启动外部编辑器的:github.com/git/git/blob/…
  • 谢谢,我会调查一下

标签: python vim scripting


【解决方案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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 2016-10-26
    相关资源
    最近更新 更多