如何在Python Git钩子中使用raw_input()? [英] How is it possible to use raw_input() in a Python Git hook?

查看:141
本文介绍了如何在Python Git钩子中使用raw_input()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Git编写一个预提交钩子,它运行pyflakes并检查修改后文件中的制表符和尾随空格()。我希望能够通过询问用户确认来覆盖挂钩,如下所示:

I am writing a pre-commit hook for Git that runs pyflakes and checks for tabs and trailing spaces in the modified files (code on Github). I would like to make it possible to override the hook by asking for user confirmation as follows:

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)

此代码产生一个错误:

This code produces an error:

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

甚至可以使用raw_input()或类似的函数在Git钩子中,如果是的话,我在做什么错误?

Is it even possible to use raw_input() or a similar function in Git hooks and if yes, what am I doing wrong?

推荐答案

您可以使用:

You could use:

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


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 box)显示PID为21802的进程的文件描述符的状态( pre-commit 进程):

Looking inside /proc/21802/fd (on this linux box) shows the state of the file descriptors for the process with PID 21802 (the pre-commit process):

  /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 可以读取。

Thus, pre-commit was spawned with sys.stdin pointing at /dev/null. sys.stdin = open('/dev/tty') redirects sys.stdin to an open filehandle from which raw_input can read.

这篇关于如何在Python Git钩子中使用raw_input()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆