python - 如何在 Python Git 钩子(Hook)中使用 raw_input()?

标签 python git githooks

我正在为 Git 编写一个预提交 Hook ,它运行 pyflakes 并检查修改后的文件 (code on Github) 中的制表符和尾随空格。我想通过如下要求用户确认来覆盖 Hook :

answer = raw_input('Commit anyway? [N/y] ')
if answer.strip()[0].lower() == 'y':
    print >> sys.stderr, 'Committing anyway.'
    sys.exit(0)
else:
    print >> sys.stderr, 'Commit aborted.'
    sys.exit(1)

此代码产生错误:

Commit anyway? [N/y] Traceback (most recent call last):
  File ".git/hooks/pre-commit", line 59, in ?
    main()
  File ".git/hooks/pre-commit", line 20, in main
    answer = raw_input('Commit anyway? [N/y] ')
EOFError: EOF when reading a line

甚至可以在 Git Hook 中使用 raw_input() 或类似函数吗?如果可以,我做错了什么?

最佳答案

你可以使用:

sys.stdin = open('/dev/tty')
answer = raw_input('Commit anyway? [N/y] ')
if answer.strip().lower().startswith('y'):
    ...

git commit电话 python .git/hooks/pre-commit :

% ps axu
...
unutbu   21801  0.0  0.1   6348  1520 pts/1    S+   17:44   0:00 git commit -am line 5a
unutbu   21802  0.1  0.2   5708  2944 pts/1    S+   17:44   0:00 python .git/hooks/pre-commit

向内看 /proc/21802/fd (在此 linux 机器上)显示 PID 为 21802 的进程(pre-commit 进程)的文件描述符状态:

  /proc/21802/fd:
  lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 0 -> /dev/null
  lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 1 -> /dev/pts/1
  lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 2 -> /dev/pts/1
  lr-x------ 1 unutbu unutbu 64 2011-09-15 17:45 3 -> /dev/tty
  lr-x------ 1 unutbu unutbu 64 2011-09-15 17:45 5 -> /dev/null

因此,pre-commit产生了 sys.stdin指向 /dev/null . sys.stdin = open('/dev/tty')重定向 sys.stdin到一个打开的文件句柄,raw_input可以阅读。

关于python - 如何在 Python Git 钩子(Hook)中使用 raw_input()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7437261/

相关文章:

python - 如何处理 "finally" block 中的异常?

git - rebase 后到 "pull"或 "push" fork 分支?

gitlab - Git 推送错误预接收 Hook 被拒绝

python - 在 django 中显示来自 tweepy python 文件的数据

Python 非贪婪正则表达式并不完全符合我的预期

python - Pygame 输入名称时使用shift

git - 使用 REST 克隆 github 存储库

git - 如何使用 git 将多个项目 fork 到一个存储库中?

php - 同步大学小组项目从 GitHub 仓库到个人服务器的更改

git - 提交后 Hook 未运行