无法自动执行git fetch&& git checkout使用python

时间:2016-01-25 18:35:43

标签: python git bitbucket

我已经自动执行了git checkout用户想要输入的特定分支的过程。我在子进程中使用以下python代码来执行此操作,

from bitbucket.bitbucket import Bitbucket
from sys import argv
import subprocess

prompt = '> '

print "Enter the name of branch you need to clone: "
user_branch = raw_input(prompt)

print "You Entered: ",user_branch


print "this will do a git status"
cmd = subprocess.Popen(["git", "status"], stdout=subprocess.PIPE)
output = cmd.communicate()[0]
print output
#for line in output: # output.split("\n"):
if  ("Untracked files:" or "Changes not staged for commit") in  output:
     print "Need to do a Git stash"
     subprocess.Popen(["git", "stash"])
     subprocess.Popen(["git fetch && git checkout"+(user_branch)])
else:
     print "simply do git checkout userbranch"
     subprocess.Popen(["git","pull"])
     subprocess.Popen(["git fetch && git checkout"+(user_branch)])

这引发:

Enter the name of branch you need to clone: 
> release_4_0
You Entered:  release_4_0
this will do a git status
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working directory clean

simply do git checkout userbranch
Traceback (most recent call last):
  File "git_updater.py", line 25, in <module>
    subprocess.Popen(["git fetch && git checkout"+(user_branch)])
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

我想只输入用户想要结帐的分支名称。这有道理吗?

1 个答案:

答案 0 :(得分:1)

subprocess.Popen(["git fetch && git checkout"+(user_branch)])

应该是

subprocess.Popen("git fetch && git checkout %s"%user_branch,shell=True)

或者你可以做像

这样的事情
subprocess.Popen(["git", "fetch"]).communicate()
subprocess.Popen(["git", "checkout", user_branch])

问题是,如果参数是一个列表,它需要逗号分隔的文件和参数(我不知道&amp;&amp;&amp;会如何工作)