git通过python子进程popen()推送并验证

rjee0c15  于 2022-12-17  发布在  Git
关注(0)|答案(1)|浏览(134)

我正在尝试在python subprocess.Popen()中使用git
到目前为止这是我的代码

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 git
subprocess.Popen([gitPath] + ['init',repoPath],cwd=repoPath)

#add remote
subprocess.Popen([gitPath] + dirList + ['remote','add','origin',repoUrl],cwd=repoPath)

#Check status, returns files to be committed etc, so a working repo exists there
subprocess.Popen([gitPath] + dirList + ['status'],cwd=repoPath)

#Adds all files in folder
subprocess.Popen([gitPath] + dirList + ['add','.'],cwd=repoPath)

#Push, gives error:
subprocess.Popen([gitPath] + dirList + ['push','origin','master],cwd=repoPath)

除了最后一个命令外,这个命令是有效的。这就是我得到这个错误的地方:

bash.exe: warning: could not find /tmp, please create!
fatal: 'git' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

当然,我不希望它工作,因为我没有把我的登录信息放在代码中的任何地方。我不知道如何添加它。我在C:/users/myUser目录下有一个文件夹/.ssh。我尝试将代码的最后一行改为:

env = {'HOME' : 'C:/users/myUser'}
subprocess.Popen([gitPath] + dirList + ['push','origin','master'],cwd=repoPath,env=env)

我希望git能找到/.ssh文件夹,但没有成功。我也尝试过不使用'dirList',但也没关系。我也尝试过将名称'origin'改为url,但也没有成功。
我不介意使用我已经创建好的.ssh密钥,或者使用带有login/password的方法,但我不想使用git库。

chhkpiq4

chhkpiq41#

此脚本中可能存在争用情况。由于git命令依赖于先前的子进程,因此先前的子进程可能无法完成,而下一个子进程出错。相反,可以使用subprocess.run()subprocess.check_ouput()启动子进程并等待其完成。可能仍需要根据布局进行调整

import subprocess
import shutil

# get a location of git
gitPath = shutil.which('git')
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 git
subprocess.run([gitPath] + ['init', repoPath], cwd=repoPath)

# add remote
subprocess.run([gitPath] + dirList + ['remote', 'add', 'origin', repoUrl], cwd=repoPath)

# check status, returns files to be committed etc, so a working repo exists there
subprocess.run([gitPath] + dirList + ['status'], cwd=repoPath)

# adds all files in folder
subprocess.run([gitPath] + dirList + ['add', '.'], cwd=repoPath)

# push
subprocess.run([gitPath] + dirList + ['push', 'origin', 'main'], cwd=repoPath)

对于credentials,可以使用Windows Credential Manager、缓存、管理器、--global等-具体取决于需要。

git config --global credential.helper cache
# or in python
subprocess.run([gitPath] + ['config', 'credential.helper', 'cache', repoPath], cwd=repoPath)

相关问题