【通过python获取git的分支名】

前言

在git开发时,编译/编译后的文件是依赖于当前的git分支名的,读取其名字,可便于后续的操作。

导入库


import subprocess

声明git指令和路径


cmd_command = "git branch --show-current"
GitBash_path = r'D:\Bitbucket\Test'

GitBash_path 是正常输入git指令的所在路径。

解析git分支名


def parse_branchname(branchname: str):
    temp = ""
    branchname = branchname[:-1]#remove string \n
    if "/" in branchname.decode('utf-8'):
        branchnamelist = branchname.decode('utf-8').split("/")
        temp = branchnamelist[1]
    else: 
        temp = branchname
    pass
    return temp

注意点:

  1. 从cmd窗口读取的字符串,末尾包含了’\n’的换行符,需删除。
  2. 有时git分支名前还包含分支类型,通过’/'分割字符串,只读取git分支名。

调用subprocess


# python version=3.6, use this code
result = subprocess.run(cmd_command, cwd=GitBash_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

current_branch = result.stdout
current_branch = parse_branchname(current_branch)

result 读取在python版本不同时代码有小区别,如果你的python版本>=3.7,请使用以下代码


# para 'text and capture_output' can be used on python version>=3.7
result = subprocess.run(cmd_command, text=True, cwd=GitBash_path, capture_output=True)

总结

通过以上的例子,可通过python脚本读取git分支名,有帮于我们后续的其他操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值