python如何使用gitbash执行git命令

python脚本,在window下执行git命令
2025-05-11 08:39:56
推荐回答(2个)
回答(1):

下面是一种解决方案

1 把gitbash 的路径放到系统的Path环境变量里 我的是 C:\Program Files (x86)\Git\bin

2 这时候 你在系统命令行里就可以用git了

3 在python里倒入 os 模块 然后执行

os.system('git') 就可以了

C:\Users\Administrator>python
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win3
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system('git')
usage: git [--version] [--help] [-C ] [-c name=value]
           [--exec-path[=]] [--html-path] [--man-path] [--info-path]
           [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
           [--git-dir=] [--work-tree=] [--namespace=]
            []

The most commonly used git commands are:
   add        Add file contents to the index
   bisect     Find by binary search the change that introduced a bug
   branch     List, create, or delete branches
   checkout   Checkout a branch or paths to the working tree
   clone      Clone a repository into a new directory
   commit     Record changes to the repository
   diff       Show changes between commits, commit and working tree, etc
   fetch      Download objects and refs from another repository
   grep       Print lines matching a pattern
   init       Create an empty Git repository or reinitialize an existing one
   log        Show commit logs
   merge      Join two or more development histories together
   mv         Move or rename a file, a directory, or a symlink
   pull       Fetch from and integrate with another repository or a local branch
   push       Update remote refs along with associated objects
   rebase     Forward-port local commits to the updated upstream head
   reset      Reset current HEAD to the specified state
   rm         Remove files from the working tree and from the index
   show       Show various types of objects
   status     Show the working tree status
   tag        Create, list, delete or verify a tag object signed with GPG

'git help -a' and 'git help -g' lists available subcommands and some
concept guides. See 'git help ' or 'git help '
to read about a specific subcommand or concept.
1
>>>

回答(2):

代码如下:

#!/usr/bin/env python# -*- coding: utf-8 -*-# 

@name   : find_t.py# @author : cat# 

@date   : 2017/8/2.import osimport timedef bash_shell(bash_command):
"""
python 中执行 bash 命令     :param bash_command:
:return: bash 命令执行后的控制台输出
"""
try:       

return os.popen(bash_command).read()().strip()    

except:        return Nonedef find_target(target_path="./../", key='.git'):
"""

查找目标目录所在的目录 : 如 

/aa/bb/.git --> return /aa/bb/
:param target_path:
:param key: target
:return:
"""
walk = os.walk(target_path)    

for super_dir, dir_names, file_names in walk:        

for dir_name in dir_names:            

if dir_name == key:

dir_full_path = os.path.join(super_dir, dir_name)                

# print(dir_full_path, super_dir, dir_name, sep=" ## ")

yield super_dirif __name__ == '__main__':

print("start execute bash ...........")

st = time.time()
cwd = os.getcwd()    

# this for repo
f

or repo_path in find_target(os.getcwd(), key='.repo'):

os.chdir(repo_path)       

if repo_path == os.getcwd():

print('find repo in -->', repo_path)

print(bash_shell('pwd'))

print(bash_shell('repo forall -c git config core.fileMode false --replace-all'))        

else:

print('error in chdir 2 {}'.format(repo_path))        

if os.getcwd() != cwd:

os.chdir(cwd)       

if os.getcwd() != cwd:

print('change 2 cwd FAIL !!!  {}'.format(cwd))    

# this for git

for git_path in find_target(os.getcwd(), key='.git'):

os.chdir(git_path)       

if git_path == os.getcwd():

print('find git in -->', git_path)

print(bash_shell('pwd'))

print(bash_shell('git config --global core.filemode false'))        

else:

print('error in chdir 2 {}'.format(git_path))        

if os.getcwd() != cwd:

os.chdir(cwd)       

if os.getcwd() != cwd:

print('change 2 cwd FAIL !!!  {}'.format(cwd))

et = time.time()

print('\n\n    

#### execute finished in {:.3f} seconds ####'.format(et - st))

print('\n')    # test for bash_command
# print(bash_shell('git init'))

# print(bash_shell('ls -al'))