我正在为 Git 编写一个预提交钩子,它运行 pyflakes 并检查修改文件中的制表符和尾随空格(Github 上的代码)。我想通过请求用户确认来覆盖钩子,如下所示:
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 hooks 中使用 raw_input() 或类似的函数,如果可以,我做错了什么?
你可以使用:
sys.stdin = open('/dev/tty')
answer = raw_input('Commit anyway? [N/y] ')
if answer.strip().lower().startswith('y'):
...
git commit
calls 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
Thus, pre-commit
产生于sys.stdin
指着/dev/null
.
sys.stdin = open('/dev/tty')
重定向sys.stdin
到一个打开的文件句柄raw_input
可以阅读。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)