하위 프로세스를 사용하지 않고 git 저장소를 복제하지 않는 Python 방법이 있습니까? 나는 당신이 추천하는 모든 종류의 모듈을 사용하고 있습니다.
git clone어쨌든 전화해야합니다 .
하위 프로세스를 사용하지 않고 git 저장소를 복제하지 않는 Python 방법이 있습니까? 나는 당신이 추천하는 모든 종류의 모듈을 사용하고 있습니다.
git clone어쨌든 전화해야합니다 .
답변:
이 GitPython은 . 이전과 내부적으로 들어 보지 못했지만 어딘가에 git 실행 파일을 가지고 있어야합니다. 또한 많은 버그가있을 수 있습니다. 그러나 시도해 볼 가치가 있습니다.
복제 방법 :
import git
git.Git("/your/directory/to/clone").clone("git://gitorious.org/git-python/mainline.git")
(좋지 않고 지원되는 방법인지 모르겠지만 작동했습니다.)
GitPython 을 사용하면 Git에 대한 좋은 파이썬 인터페이스를 얻을 수 있습니다.
예를 들어 설치 후 ( pip install gitpython) 새 저장소를 복제하려면 clone_from 함수를 사용할 수 있습니다 .
from git import Repo
Repo.clone_from(git_url, repo_dir)
Repo 객체 사용에 대한 예제 는 GitPython 자습서 를 참조하십시오 .
참고 : GitPython은 시스템에 git이 설치되어 있어야하며 시스템의 PATH를 통해 액세스 할 수 있어야합니다.
내 솔루션은 매우 간단하고 간단합니다. 암호 / 암호를 수동으로 입력 할 필요조차 없습니다.
내 완전한 코드는 다음과 같습니다.
import sys
import os
path = "/path/to/store/your/cloned/project"
clone = "git clone gitolite@<server_ip>:/your/project/name.git"
os.system("sshpass -p your_password ssh user_name@your_localhost")
os.chdir(path) # Specifying the path where the cloned project needs to be copied
os.system(clone) # Cloning
os.getcwd()변경하기 전에 실제 작업 디렉토리를 기억하고 os.chdir(...)나중에 다시 재설정하는 것이 좋습니다.
git clone <repo_url> <target_path>. 사용할 필요가 없습니다chdir
GitPython 으로 리포지토리 를 복제하는 동안 진행 상황을 인쇄하는 방법은 다음과 같습니다.
import time
import git
from git import RemoteProgress
class CloneProgress(RemoteProgress):
def update(self, op_code, cur_count, max_count=None, message=''):
if message:
print(message)
print('Cloning into %s' % git_root)
git.Repo.clone_from('https://github.com/your-repo', '/your/repo/dir',
branch='master', progress=CloneProgress())
Python 3의 경우
첫 번째 설치 모듈 :
pip3 install gitpython
나중에 코딩하십시오 :)
import os
from git.repo.base import Repo
Repo.clone_from("https://github.com/*****", "folderToSave")
도움이 되었기를 바랍니다.
아주 간단한 방법은 url에 creds를 전달하는 것입니다.하지만 약간 의심 스러울 수 있습니다.주의해서 사용하세요.
import os
def getRepo(repo_url, login_object):
'''
Clones the passed repo to my staging dir
'''
path_append = r"stage\repo" # Can set this as an arg
os.chdir(path_append)
repo_moddedURL = 'https://' + login_object['username'] + ':' + login_object['password'] + '@github.com/UserName/RepoName.git'
os.system('git clone '+ repo_moddedURL)
print('Cloned!')
if __name__ == '__main__':
getRepo('https://github.com/UserName/RepoYouWant.git', {'username': 'userName', 'password': 'passWord'})
gitpython 모듈을 사용하는 gitpull 및 gitpush의 샘플 코드입니다.
import os.path
from git import *
import git, os, shutil
# create local Repo/Folder
UPLOAD_FOLDER = "LocalPath/Folder"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
print(UPLOAD_FOLDER)
new_path = os.path.join(UPLOADFOLDER)
DIR_NAME = new_path
REMOTE_URL = "GitURL" # if you already connected with server you dont need to give
any credential
# REMOTE_URL looks "git@github.com:path of Repo"
# code for clone
class git_operation_clone():
try:
def __init__(self):
self.DIR_NAME = DIR_NAME
self.REMOTE_URL = REMOTE_URL
def git_clone(self):
if os.path.isdir(DIR_NAME):
shutil.rmtree(DIR_NAME)
os.mkdir(DIR_NAME)
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
except Exception as e:
print(str(e))
# code for push
class git_operation_push():
def git_push_file(self):
try:
repo = Repo(DIR_NAME)
commit_message = 'work in progress'
# repo.index.add(u=True)
repo.git.add('--all')
repo.index.commit(commit_message)
origin = repo.remote('origin')
origin.push('master')
repo.git.add(update=True)
print("repo push succesfully")
except Exception as e:
print(str(e))
if __name__ == '__main__':
a = git_operation_push()
git_operation_push.git_push_file('')
git_operation_clone()
git_operation_clone.git_clone('')