【问题标题】:Why `git pull` doesn't work when executed from within a Python script?为什么 `git pull` 在 Python 脚本中执行时不起作用?
【发布时间】:2023-02-21 16:08:54
【问题描述】:

我正在尝试使用 subprocess 模块在存储库中执行 git pull 操作。问题是其他命令,例如git status 可以正常工作,但git pull 却不行。不生成任何输出。

这就是我被困的地方:

import subprocess

subprocess.check_output(
  ['git', 'pull', 'origin', 'main']
)

执行时,抛出以下错误:

[WinError 6] The handle is invalid

我还使用 os.chdircwd 将目录上下文更改为目标存储库,但它没有按预期工作:

import os
import subprocess

os.chdir(my_repository_dir)

subprocess.check_output(
  ['git', 'pull', 'origin', 'main'],
  cwd=my_repository_dir
)

以下subprocess 方法均无效:check_outputcheck_callrunPopen。是否使用 shell 属性。

此外,我访问了 GitPython 模块,但它也不起作用。

我的 Python 脚本运行在视窗服务器 2022,安装的Python版本为3.6.8git pull 指令在公开的 Flask 应用程序处理传入的 HTTP 请求时进行评估。

目标目录是有效的 Git 存储库。

我已经在 Gitlab 上包含了 SSH 密钥,并且帐户凭据存储在Windows 凭据管理器.

如果 git pull 不打算从脚本中调用,我想了解执行此操作的正确方法。

【问题讨论】:

  • @brian DEVNULL 旨在丢弃它收到的任何信息。所以,我认为它会忽略错误但不会解决问题。
  • 这个问题是关于子进程使用的 STDIN 句柄。这对子进程写入 STDOUT/STDERR 的内容或方式没有影响。
  • @brian 我遇到过这个问题,但即使使用其他特殊值,如 DEVNULL、PIPE、STDOUT 等,我也无法获得任何相关结果:/

标签: python python-3.x git gitlab


【解决方案1】:

this library中查看check_outputgit命令的其他用法,您可以尝试:

result = subprocess.check_output('git pull', shell=True, stderr=subprocess.STDOUT).decode()
print(result)

通过将 stderr 流重定向到与 stdout 相同的输出,您一定会捕获到所有内容。
考虑到most git commands outputs information message on stderr,这很重要。

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 2017-10-17
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多