Python操作git
生活随笔
收集整理的這篇文章主要介紹了
Python操作git
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、Git版本管理
很多公司在使用git的tag進行版本的管理。
git tag -n 查看本地Tag git tag -l 'v1.4.2.*' 查看本地Tag,模糊匹配 git show v1.0 查看git tag -a v1.0 -m '版本介紹' 本地創建Tag git tag -d v1.0 刪除Tag git checkout v.10 切換taggit push origin --tags 推送本地tag到遠程 git pull origin --tags 獲取遠程taggit clone -b v0.10 http://... 指定版本克隆代碼二、Python操作git
""" 基于Python實現對git倉庫進行操作,使用前需要安裝模塊:gitpythonpip3 install gitpython """# ############## 1. clone下載代碼 ############## """ import os from git.repo import Repodownload_path = os.path.join('code', 'fuck') Repo.clone_from('https://gitee.com/wupeiqi/fuck.git', to_path=download_path, branch='master') """# ############## 2. pull最新代碼 ############## """ import os from git.repo import Repolocal_path = os.path.join('code', 'fuck') repo = Repo(local_path) repo.git.pull() """ # ############## 3. 獲取所有分支 ############## """ import os from git.repo import Repolocal_path = os.path.join('code', 'fuck') repo = Repo(local_path)branches = repo.remote().refs for item in branches:print(item.remote_head) """ # ############## 4. 獲取所有版本 ############## """ import os from git.repo import Repolocal_path = os.path.join('code', 'fuck') repo = Repo(local_path)for tag in repo.tags:print(tag.name) """# ############## 5. 獲取所有commit ############## """ import os from git.repo import Repolocal_path = os.path.join('code', 'fuck') repo = Repo(local_path)commit_log = repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50,date='format:%Y-%m-%d %H:%M') log_list = commit_log.split("\n") real_log_list = [eval(item) for item in log_list] print(real_log_list) """# ############## 6. 切換分支 ############## """ import os from git.repo import Repolocal_path = os.path.join('code', 'fuck') repo = Repo(local_path)before = repo.git.branch() print(before) repo.git.checkout('master') after = repo.git.branch() print(after) repo.git.reset('--hard', '854ead2e82dc73b634cbd5afcf1414f5b30e94a8') """# ############## 7. 打包代碼 ############## """ with open(os.path.join('code', 'fuck.tar'), 'wb') as fp:repo.archive(fp) """git相關操作類
import os from git.repo import Repo from git.repo.fun import is_git_dirclass GitRepository(object):"""git倉庫管理"""def __init__(self, local_path, repo_url, branch='master'):self.local_path = local_pathself.repo_url = repo_urlself.repo = Noneself.initial(repo_url, branch)def initial(self, repo_url, branch):"""初始化git倉庫:param repo_url::param branch::return:"""if not os.path.exists(self.local_path):os.makedirs(self.local_path)git_local_path = os.path.join(self.local_path, '.git')if not is_git_dir(git_local_path):self.repo = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch)else:self.repo = Repo(self.local_path)def pull(self):"""從線上拉最新代碼:return:"""self.repo.git.pull()def branches(self):"""獲取所有分支:return:"""branches = self.repo.remote().refsreturn [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]def commits(self):"""獲取所有提交記錄:return:"""commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',max_count=50,date='format:%Y-%m-%d %H:%M')log_list = commit_log.split("\n")return [eval(item) for item in log_list]def tags(self):"""獲取所有tag:return:"""return [tag.name for tag in self.repo.tags]def change_to_branch(self, branch):"""切換分值:param branch::return:"""self.repo.git.checkout(branch)def change_to_commit(self, branch, commit):"""切換commit:param branch::param commit::return:"""self.change_to_branch(branch=branch)self.repo.git.reset('--hard', commit)def change_to_tag(self, tag):"""切換tag:param tag::return:"""self.repo.git.checkout(tag)if __name__ == '__main__':local_path = os.path.join('codes', 'luffycity')repo = GitRepository(local_path, 'https://gitee.com/wupeiqi/fuck.git')branch_list = repo.branches()print(branch_list)repo.change_to_branch('dev')repo.pull()三、Python解壓縮文件
在py2和py3中對文件進行解壓縮稍有不同。
- shutil 模塊【壓縮支持py2和py3,解壓只支持py3】
- tarfile / zipfile模塊【支持py2和py3】
shutil模塊
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import shutil# 文件壓縮 """ ret = shutil.make_archive(base_name="code/www", # 壓縮包文件路勁format='zip', # “zip”, “tar”root_dir='code/fuck' # 被壓縮的文件件 ) print(ret) """# 解壓文件 """ shutil._unpack_zipfile('code/www.zip', 'code/new') shutil._unpack_tarfile('code/www.tar', 'code/new') """zipfile模塊
import zipfile# 壓縮 z = zipfile.ZipFile('laxi.zip', 'w') z.write('a.log') z.write('data.data') z.close()# 解壓 z = zipfile.ZipFile('laxi.zip', 'r') z.extractall() z.close()tarfile模塊
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import tarfile# 壓縮 tar = tarfile.open('your.tar', 'w') tar.add('utils/codes/luffycity/a1.py') tar.add('utils/codes/luffycity/a3.py') tar.close()# 解壓 tar = tarfile.TarFile('code/www.tar', 'r') tar.extractall(path='/code/x1/') # 可設置解壓地址 tar.close()四、執行本地命令
import subprocessresult = subprocess.check_output('ls -l', cwd='/Users/wupeiqi/PycharmProjects', shell=True) print(result.decode('utf-8'), type(result))五、Paramiko執行遠程操作
import paramikoclass SSHProxy(object):def __init__(self, hostname, port, username, private_key_path):self.hostname = hostnameself.port = portself.username = usernameself.private_key_path = private_key_pathself.transport = Nonedef open(self):private_key = paramiko.RSAKey.from_private_key_file(self.private_key_path)self.transport = paramiko.Transport((self.hostname, self.port))self.transport.connect(username=self.username, pkey=private_key)def close(self):self.transport.close()def command(self, cmd):ssh = paramiko.SSHClient()ssh._transport = self.transportstdin, stdout, stderr = ssh.exec_command(cmd)result = stdout.read()#ssh.close()return resultdef upload(self, local_path, remote_path):sftp = paramiko.SFTPClient.from_transport(self.transport)sftp.put(local_path, remote_path)sftp.close()def __enter__(self):self.open()return selfdef __exit__(self, exc_type, exc_val, exc_tb):self.close()if __name__ == '__main__':with SSHProxy('10.211.55.25', 22, 'root', '/Users/wupeiqi/.ssh/id_rsa') as ssh:# v1 = ssh.command('sudo ifconfig')# print(v1)ssh.upload('your.tar', '/data/your.tar')六、殺進程
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' #!/usr/bin/env python # -*- coding:utf-8 -*- import os import signal import subprocessoutput = subprocess.check_output("pgrep -f python", shell=True) pid_list = map(int, output.split()) for pid in pid_list:os.kill(pid, signal.SIGKILL)七、其他
salt操作
#!/usr/bin/env python # -*- coding:utf-8 -*- """ SaltAPI推送文件 """# #### 基于SSH:API #### """ from salt.client.ssh.client import SSHClient client = SSHClient()# 執行命令 # result = client.cmd('*', 'cmd.run', ('ls',))# 調用grains # ret = client.cmd('*','grains.items')# 調用pillar # ret = client.cmd('*','pillar.items')# 執行 state # ret = client.cmd('*','state.sls',('fengfeng','pillar={"xxxx":"luffy"}'))# 發送文件 # ret = client.cmd('*','cp.get_file',('salt://fengfeng/files/test.conf','/data/s1.conf'))# 發送文件 # ret = client.cmd('*','cp.get_url',('http://www.pythonav.com/allstatic/imgs/mv/picture/2.jpeg','/data/s1.jpeg')) """ # #### 基于Master:API #### """ import salt.client local = salt.client.LocalClient()# 執行命令 # result = client.cmd('*', 'cmd.run', ('ls',))# 調用grains # ret = client.cmd('*','grains.items')# 調用pillar # ret = client.cmd('*','pillar.items')# 執行 state # ret = client.cmd('*','state.sls',('fengfeng','pillar={"xxxx":"luffy"}'))# 發送文件 # ret = client.cmd('*','cp.get_file',('salt://fengfeng/files/test.conf','/data/s1.conf'))# 發送文件 # ret = client.cmd('*','cp.get_url',('http://www.pythonav.com/allstatic/imgs/mv/picture/2.jpeg','/data/s1.jpeg')) """發布功能
######## 1. 執行命令 #!/usr/bin/env python # -*- coding:utf-8 -*- import subprocess import commandsresult = subprocess.check_output('ls', cwd='/Users/wupeiqi/PycharmProjects', shell=True) print(result, type(result))ret = commands.getoutput("pgrep -f python") print(ret)######## 2. 解壓縮文件 # !/usr/bin/env python # -*- coding:utf-8 -*-import shutil# 文件壓縮 """ ret = shutil.make_archive(base_name="/Users/wupeiqi/PycharmProjects/deploy27/前戲/wwwwwwwwww",format='gztar', # “zip”, “tar”, “bztar”,“gztar”root_dir='/Users/wupeiqi/PycharmProjects/deploy27/deploy' ) print(ret) """# 文件解壓 import tarfile import zipfile# shutil._unpack_zipfile(file.stream, upload_path) """ tar = tarfile.open('/Users/wupeiqi/PycharmProjects/deploy27/前戲/wwwwwwwwww.tar.gz', 'r') tar.extractall(path='/Users/wupeiqi/PycharmProjects/deploy27/前戲/dp/') # 可設置解壓地址 tar.close() """######## 3. 遍歷文件夾下的所有文件 # !/usr/bin/env python # -*- coding:utf-8 -*- import osfor item in os.listdir('/Users/wupeiqi/PycharmProjects/deploy27/deploy'):print(item)for item in os.walk('/Users/wupeiqi/PycharmProjects/deploy27/deploy'):print(item)######## 4. 重命名和刪除 # !/usr/bin/env python # -*- coding:utf-8 -*- import shutil# shutil.move('/Users/wupeiqi/PycharmProjects/deploy27/deploy1','/Users/wupeiqi/PycharmProjects/deploy27/deploy')# shutil.rmtree('/Users/wupeiqi/PycharmProjects/deploy27/t')######## 5. 殺進程 # !/usr/bin/env python # -*- coding:utf-8 -*- import os import signal import subprocess import commandsoutput = subprocess.check_output("pgrep -f python", shell=True) pid_list = map(int, output.split()) for pid in pid_list:os.kill(pid, signal.SIGKILL)######## 6. salt推送文件 # !/usr/bin/env python # -*- coding:utf-8 -*- """ SaltAPI推送文件 """# #### 基于SSH:API #### """ from salt.client.ssh.client import SSHClient client = SSHClient()# 執行命令 # result = client.cmd('*', 'cmd.run', ('ls',))# 調用grains # ret = client.cmd('*','grains.items')# 調用pillar # ret = client.cmd('*','pillar.items')# 執行 state # ret = client.cmd('*','state.sls',('fengfeng','pillar={"xxxx":"luffy"}'))# 發送文件 # ret = client.cmd('*','cp.get_file',('salt://fengfeng/files/test.conf','/data/s1.conf'))# 發送文件 # ret = client.cmd('*','cp.get_url',('http://www.pythonav.com/allstatic/imgs/mv/picture/2.jpeg','/data/s1.jpeg')) """ # #### 基于Master:API #### """ import salt.client local = salt.client.LocalClient()# 執行命令 # result = client.cmd('*', 'cmd.run', ('ls',))# 調用grains # ret = client.cmd('*','grains.items')# 調用pillar # ret = client.cmd('*','pillar.items')# 執行 state # ret = client.cmd('*','state.sls',('fengfeng','pillar={"xxxx":"luffy"}'))# 發送文件 # ret = client.cmd('*','cp.get_file',('salt://fengfeng/files/test.conf','/data/s1.conf'))# 發送文件 # ret = client.cmd('*','cp.get_url',('http://www.pythonav.com/allstatic/imgs/mv/picture/2.jpeg','/data/s1.jpeg')) """總結
以上是生活随笔為你收集整理的Python操作git的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python内部类
- 下一篇: 用python修改文件内容修改txt内容