我如何以编程方式发现git使用的编辑器,跨平台?

时间:2017-05-25 01:04:49

标签: python git editor

假设我们在Python环境中,我们可能在Windows,OSX或Linux上。

我们如何确定git使用的编辑器?

如果它只是环境变量,我们可以这样做:

os.getenv('GIT_EDITOR')

但它也可以在配置中。

可以解析git配置文件,但我们不想重新实现整个搜索(回购,用户,系统?)。

问题:

我们如何以编程方式发现git使用的编辑器?

1 个答案:

答案 0 :(得分:6)

运行git var GIT_EDITOR。结果输出是要使用的编辑器的名称,适合传递给shell:

import subprocess

def git_var(what):
    "return GIT_EDITOR or GIT_PAGER, for instance"
    proc = subprocess.Popen(['git', 'var', what], shell=False,
        stdout=subprocess.PIPE)
    output = proc.stdout.read()
    status = proc.wait()
    if status != 0:
        ... raise some error ...
    output = output.rstrip(b'\n')
    output = output.decode('utf8', errors='ignore') # or similar for py3k
    return output

(当然,你是否以及如何对字节进行字符串化)。

相关问题