将check_call语句转换为subprocess.Popen

时间:2012-12-29 19:50:41

标签: python subprocess

我在将check_call语句转换为subprocess.Popen时遇到了以下错误,我正在弄乱“&&”我想,有人可以帮忙解决这个问题吗?

check_call("git fetch ssh://username@company.com:29418/platform/vendor/company-proprietary/radio %s && git cherry-pick FETCH_HEAD" % change_ref , shell=True)
proc = subprocess.Popen(['git', 'fetch', 'ssh://username@company.com:29418/platform/vendor/company-proprietary/radio', change_ref , '&& git' , 'cherry-pick', 'FETCH_HEAD'], stderr=subprocess.PIPE)

Error:-

fatal: Invalid refspec '&& git

2 个答案:

答案 0 :(得分:1)

&&是一个shell功能。单独运行命令:

proc = subprocess.Popen(['git', 'fetch', 'ssh://username@company.com:29418/platform/vendor/company-proprietary/radio', change_ref], stderr=subprocess.PIPE)
out, err = proc.communicate()  # Wait for completion, capture stderr

# Optional: test if there were no errors
if not proc.returncode:
    proc = subprocess.Popen(['git' , 'cherry-pick', 'FETCH_HEAD'], stderr=subprocess.PIPE)
    out, err = proc.communicate()

答案 1 :(得分:1)

rc = Popen("cmd1 && cmd2", shell=True).wait()
if rc != 0:
   raise Error(rc)

或者

rc = Popen(["git", "fetch", "ssh://...", change_ref]).wait()
if rc != 0:
   raise Error("git fetch failed: %d" % rc)
rc = Popen("git cherry-pick FETCH_HEAD".split()).wait()
if rc != 0:
   raise Error("git cherry-pick failed: %d" % rc)

捕获stderr

proc_fetch = Popen(["git", "fetch", "ssh://...", change_ref], stderr=PIPE)
stderr = proc_fetch.communicate()[1]
if p.returncode == 0: # success
   p = Popen("git cherry-pick FETCH_HEAD".split(), stderr=PIPE)
   stderr = p.communicate()[1]
   if p.returncode != 0: # cherry-pick failed
      # handle stderr here
      ...
else: # fetch failed
    # handle stderr here
    ...