python执行git_通过git钩子执行python子进程

本文探讨了在使用Python编写的Git钩子脚本中执行git log命令时遇到的问题,即该命令无法正确识别当前目录为Git仓库。文中详细介绍了作者尝试的多种解决方案,包括设置--git-dir选项、使用GIT_DIR环境变量以及同时指定cwd和GIT_DIR变量的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm running Gitolite over the Git repository and I have post-receive hook there written in Python. I need to execute "git" command at git repository directory. There are few lines of code:

proc = subprocess.Popen(['git', 'log', '-n1'], cwd='/home/git/repos/testing.git' stdout=subprocess.PIPE, stderr=subprocess.PIPE)

proc.communicate()

After I make new commit and push to repository, scripts executes and says

fatal: Not a git repository: '.'

If I run

proc = subprocess.Popen(['pwd'], cwd='/home/git/repos/testing.git' stdout=subprocess.PIPE, stderr=subprocess.PIPE)

it says, as expected, correct path to git repository (/home/git/repos/testing.git)

If I run this script manually from bash, it works correct and show correct output of "git log". What I'm doing wrong?

解决方案

You could try to set the git repository using a command-line switch:

proc = subprocess.Popen(['git', '--git-dir', '/home/git/repos/testing.git', 'log', '-n1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

--git-dir needs to point to an actual git directory (.git in a working tree). Note that for some commands you also need to set a --work-tree option too.

Another way to set the directory is using the GIT_DIR environment variable:

import os

env = os.environ.copy()

env['GIT_DIR'] = '/home/git/repos/testing.git'

proc = subprocess.Popen((['git', 'log', '-n1', stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)

Apparently hooks already set GIT_DIR but obviously this is incorrect for your case (it could be relative); the above code sets it to a full, explicit path.

Edit: Apparently it only works for the OP when specifying both a cwd and overriding the GIT_DIR var:

import os

repo = '/home/git/repos/testing.git'

env = os.environ.copy()

env['GIT_DIR'] = repo

proc = subprocess.Popen((['git', 'log', '-n1', stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=repo)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值