简体   繁体   中英

Running Git clone command in Python

I am new to both Python and Git. I am in the process of writing a Python script which needs to do the same action as done by running the below git command from my workspace on a Linux server. (ie /local/mnt/workspace/)

git clone git://git.xyz.com/platform/manifest.git -b jb_2.5

I tried using Fab library however module fabric.api isn't installed so I couldn't proceed. Also,

import git
git.Git().clone("git://git.xyz.com/platform/manifest.git") 

didn't work.

Any other solutions to do this ? Would appreciate the help. Thanks.

You can define a git function that allows you to make calls to git. Limiting the user to git commands is important for security purposes; otherwise asking for a git url and using other techniques could result in loss of data or other malicious attacks.

import subprocess

def git(*args):
    return subprocess.check_call(['git'] + list(args))

# examples
git("status")
git("clone", "git://git.xyz.com/platform/manifest.git", "-b", "jb_2.5")

Changing it to subprocess.check_output allows you to see the output git prints, instead of determining success (eg git("status") raises an exception if you're not in a git repo).


Side note: take a look at PIP which is designed to help install common packages.

你可以掏出(通过os.systemsubprocess ),或使用GitPython包。

Since you didn't show what the error was beyond "didn't work", it's hard to guess what exactly your problem was.

But I'm guessing the problem is that import git raised an ImportError , because you never installed the git module that you're trying to use.

If so, the exact same readme document that told you how to do git.Git().clone("git://git.xyz.com/platform/manifest.git") will also tell you how to install it.

But most likely, all you need is something like pip install pygit2 or pip install GitPython or something like that. (You may need sudo , and you may need to install pip before you can use it, and so on, but since we know nothing about your platform or your level of knowledge, there's no way to guess exactly what you need.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM