【问题标题】:How is it possible to use raw_input() in a Python Git hook?如何在 Python Git 挂钩中使用 raw_input()?
【发布时间】:2011-09-15 20:48:22
【问题描述】:

我正在为 Git 编写一个预提交挂钩,它运行 pyflakes 并检查修改后的文件 (code on 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() 或类似函数,如果可以,我做错了什么?

【问题讨论】:

    标签: python git githooks


    【解决方案1】:

    你可以使用:

    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/nullsys.stdin = open('/dev/tty')sys.stdin 重定向到一个打开的文件句柄,raw_input 可以从中读取。

    【讨论】:

      【解决方案2】:

      在 shell 中你可以:

      read ANSWER < /dev/tty
      

      【讨论】:

        猜你喜欢
        • 2013-07-10
        • 2020-08-22
        • 2021-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-27
        相关资源
        最近更新 更多