繁体   English   中英

通过git hook执行python子进程

[英]Executing python subprocess via git hook

我在Git存储库上运行Gitolite,并且在那里用Python编写了接收后钩子。 我需要在git存储库目录中执行“ git”命令。 有几行代码:

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

在我进行新的提交并推送到存储库后,脚本执行并说

fatal: Not a git repository: '.'

如果我跑步

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

它像预期的那样显示了git仓库的正确路径(/home/git/repos/testing.git)

如果我从bash手动运行此脚本,它将正常工作并显示“ git log”的正确输出。 我做错了什么?

您可以尝试使用命令行开关设置git存储库:

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

--git-dir需要指向实际的git目录(工作树中的.git )。 请注意,对于某些命令,您需要设置--work-tree选项。

设置目录的另一种方法是使用GIT_DIR环境变量:

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)

显然,钩子已经设置了GIT_DIR但是显然这对于​​您的情况是不正确的(可能是相对的); 上面的代码将其设置为完整的显式路径。

参见git联机帮助页

编辑:显然,它仅在指定cwd并覆盖GIT_DIR var时才适用于OP:

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)

cwd参数后缺少逗号:

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

暂无
暂无

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

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