尝试使用 python 脚本执行 git 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9774972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 06:37:25  来源:igfitidea点击:

trying to execute git command using python script

pythongit

提问by Rakesh

I am trying to execute a simple git command using following python script.

我正在尝试使用以下 python 脚本执行一个简单的 git 命令。

#!/usr/bin/python

import commands
import subprocess
import os
import sys

pr = subprocess.Popen( "/usr/bin/git log" , cwd = os.path.dirname( '/ext/home/rakesh.kumar/workspace/myproject' ), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
(out, error) = pr.communicate()


print "Error : " + str(error) 
print "out : " + str(out)

but I am getting the following error even though I am running the python script in the same directory where git reposetory is.

但是即使我在 git repository 所在的同一目录中运行 python 脚本,我也收到以下错误。

Error : fatal: Not a git repository (or any of the parent directories): .git

I suspected the git might got correputed, but git files are fine and git commands work if I execute on normal command prompt.

我怀疑 git 可能会被修正,但是如果我在正常的命令提示符下执行,git 文件很好,并且 git 命令可以工作。

I tried to search on net but couldn't get useful information. Please help it will be greatly appreciated.

我试图在网上搜索但无法获得有用的信息。请帮助它将不胜感激。

采纳答案by Adam

Try this:

尝试这个:

#!/usr/bin/python

import commands
import subprocess
import os
import sys

pr = subprocess.Popen( "/usr/bin/git log" , cwd = os.path.dirname( '/ext/home/rakesh.kumar/workspace/myproject/' ), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
(out, error) = pr.communicate()


print "Error : " + str(error) 
print "out : " + str(out)

Directory path should have '/' at the end.

目录路径末尾应该有“/”。

回答by Santa

The problem is your use of os.path.dirname():

问题是您使用了os.path.dirname()

os.path.dirname( '/ext/home/rakesh.kumar/workspace/myproject' )

will give you:

会给你:

>>> os.path.dirname( '/ext/home/rakesh.kumar/workspace/myproject' )
'/ext/home/rakesh.kumar/workspace'

which, I bet, is not what you want.

我敢打赌,这不是您想要的。