【问题标题】:Git add through python subprocessgit通过python子进程添加
【发布时间】:2015-10-24 08:12:28
【问题描述】:

我正在尝试通过 python 子进程运行 git 命令。我通过调用github的cmd目录下的git.exe来做到这一点。

我设法让大多数命令正常工作(初始化、远程、状态),但在调用 git add 时出现错误。到目前为止,这是我的代码:

import subprocess

gitPath = 'C:/path/to/git/cmd.exe'
repoPath = 'C:/path/to/my/repo'
repoUrl = 'https://www.github.com/login/repo';

#list to set directory and working tree
dirList = ['--git-dir='+repoPath+'/.git','--work-tree='+repoPath]


#init gitt
subprocess.call([gitPath] + ['init',repoPath]

#add remote
subprocess.call([gitPath] + dirList + ['remote','add','origin',repoUrl])

#Check status, returns files to be commited etc, so a working repo exists there
subprocess.call([gitPath] + dirList + ['status'])

#Adds all files in folder (this returns the error)
subprocess.call([gitPath] + dirList + ['add','.']

我得到的错误是:

fatal: Not a git repository (or any of the parent directories): .git

所以我搜索了这个错误,我发现的大多数解决方案都是关于不在正确的目录中。所以我的猜测也是这样。但是,我不知道为什么。 Git状态返回目录中的正确文件,我设置了--git-dir和--work-tree

如果我转到 git shell,我添加文件没有问题,但我无法找出这里出错的原因。

我不是在寻找使用 pythons git 库的解决方案。

【问题讨论】:

    标签: python git github cmd subprocess


    【解决方案1】:

    您需要指定工作目录。

    函数Popencallcheck_callcheck_output 有一个cwd 关键字参数来执行此操作,例如:

    subprocess.call([gitPath] + dirList + ['add','.'], cwd='/home/me/workdir')
    

    另见Specify working directory for popen

    【讨论】:

      【解决方案2】:

      除了使用cwdPopen 的参数,你还可以使用git 的标志-C:

      usage: git [--version] [--help] [-C <path>] [-c name=value]
                 [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
                 [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
                 [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
                 <command> [<args>]
      

      所以应该是这样的

      subprocess.Popen('git -C <path>'...)
      

      【讨论】:

        【解决方案3】:

        在 Python 2 中,这对我有用。

        import subprocess 
        
        subprocess.Popen(['git', '--git-dir', '/path/.git', '--work-tree', '/work/dir', 'add', '/that/you/add/file'])
        

        【讨论】:

        • 谢谢@Hemaamathavan ,只是为了注册你用过哪个python版本?
        • 我正在使用 python 2.7
        • 谢谢@Hemaamathavan,有人在python3中试过这个?
        【解决方案4】:

        从 Python 3.5 开始,您可以为此使用 subprocess.run

        subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None , errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)¶

        import subprocess
        subprocess.run(["git", "clone", "https://github.com/VundleVim/Vundle.vim.git", folder], check=True, stdout=subprocess.PIPE)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-31
          • 2013-06-08
          • 2020-05-16
          • 1970-01-01
          • 2019-07-21
          • 1970-01-01
          • 2012-10-14
          • 2017-07-08
          相关资源
          最近更新 更多