You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编写Git commit-msg钩子调用input()触发EOFError问题求解

问题根因

Git运行所有钩子脚本时,默认会将标准输入流重定向到/dev/null,你的代码中调用input()函数尝试读取用户输入时,直接读到了文件结束符,因此触发EOFError报错。

修复方案

在读取用户输入前,将标准输入重新绑定到当前终端设备即可:

  • 类Unix系统(Linux/macOS)的终端设备路径为/dev/tty
  • Windows系统的终端设备路径为CON

你只需要在while True循环读取用户输入前,添加一行重定向标准输入的代码即可。另外你原代码存在变量作用域隐患:如果提交信息所有行都是注释行,循环结束后line变量未定义,正则匹配会报错,建议补充兜底处理。

修改后可正常运行的代码
#!/usr/bin/python
import sys
import re

def main():
    commit_msg = ""
    # 读取提交信息有效内容
    with open(sys.argv[1], "r") as fp:
        lines = fp.readlines()
        for idx, line in enumerate(lines):
            if line.strip() == "# ------------------------ >8 ------------------------":
                break
            if line[0] == "#":
                continue
            commit_msg += line

    # 校验提交信息是否包含关联issue编号
    if (re.search('#[0-9]+$', commit_msg) is None):
        print("Warning: add issue number related to this commit.")
        # 重定向标准输入到当前终端,解决无法读取用户输入的问题
        sys.stdin = open('/dev/tty', 'r')
        # 循环等待用户有效输入
        try:
            while True:
                response = input("Are you sure you want to commit? [y/N]: ")
                if (response == 'y'):
                    sys.exit(0)
                elif (response == 'N'):
                    sys.exit(1)
        except EOFError as e:
            print(e)
            sys.exit(1)
    
    # 校验通过
    print("Success: Perfect commit!")
    sys.exit(0)    

if __name__ == "__main__":
    main()

内容的提问来源于stack exchange,提问作者Sun Jing Woo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:06:07