djq*_*djq 65 python git bash github
使用github webhooks,我希望能够将任何更改提取到远程开发服务器.目前,在适当的目录中,git pull获取需要进行的任何更改.但是,我无法弄清楚如何从Python中调用该函数.我尝试过以下方法:
import subprocess
process = subprocess.Popen("git pull", stdout=subprocess.PIPE)
output = process.communicate()[0]
Run Code Online (Sandbox Code Playgroud)
但这会导致以下错误
回溯(最近调用最后一次):文件"",第1行,在文件"/usr/lib/python2.7/subprocess.py",第679行,在 init errread,errwrite)文件"/ usr/lib/python2. 7/subprocess.py",第1249行,在_execute_child中引发child_exception OSError:[Errno 2]没有这样的文件或目录
有没有办法可以在Python中调用这个bash命令?
jle*_*ahy 122
你考虑过使用GitPython吗?它旨在为您处理所有这些废话.
import git
g = git.cmd.Git(git_dir)
g.pull()
Run Code Online (Sandbox Code Playgroud)
https://github.com/gitpython-developers/GitPython
phi*_*hag 38
subprocess.Popen期望一个程序名称和参数的列表.你传给它一个字符串,它是(默认shell=False)相当于:
['git pull']
Run Code Online (Sandbox Code Playgroud)
这意味着子进程试图找到一个名为字面的程序git pull,但未能这样做:在Python 3.3中,您的代码引发了异常FileNotFoundError: [Errno 2] No such file or directory: 'git pull'.相反,传入一个列表,如下所示:
import subprocess
process = subprocess.Popen(["git", "pull"], stdout=subprocess.PIPE)
output = process.communicate()[0]
Run Code Online (Sandbox Code Playgroud)
顺便说一句,在Python 2.7+中,您可以使用check_output便捷功能简化此代码:
import subprocess
output = subprocess.check_output(["git", "pull"])
Run Code Online (Sandbox Code Playgroud)
另外,要使用git功能,调用git二进制文件绝对不需要(尽管简单和可移植).考虑使用git-python或Dulwich.
Eri*_*ric 25
使用GitPython的公认答案比直接使用好一点subprocess。
这种方法的问题在于,如果您想解析输出,您最终会查看“瓷器”命令的结果,这是一个坏主意
以这种方式使用 GitPython 就像获得一个闪亮的新工具箱,然后将它用于将它固定在一起的一堆螺丝而不是里面的工具。以下是 API 的设计用途:
import git
repo = git.Repo('Path/to/repo')
repo.remotes.origin.pull()
Run Code Online (Sandbox Code Playgroud)
如果你想检查是否有变化,你可以使用
current = repo.head.commit
repo.remotes.origin.pull()
if current != repo.head.commit:
print("It changed")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63232 次 |
| 最近记录: |