繁体   English   中英

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

[英]How is it possible to use raw_input() in a Python Git hook?

我正在为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钩子中使用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

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

在shell中你可以:

read ANSWER < /dev/tty

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM