我正在为 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/