2012-12-26 35 views

Trả lời

19

returncode thực sự là câu trả lời, nhưng giải pháp không cần phải phức tạp.

process = subprocess.Popen(...) 
stdoutdata, stderrdata = process.communicate() 
print process.returncode 

Thông tin thêm trong Python subprocess docs.

+0

là '' wait'' thực sự cần thiết hoặc không '' giao tiếp() '' mất những điều khi quá trình này vẫn đang chạy? – user248237dfsf

+5

@ user248237 Các tài liệu nói "mã trả về, được đặt bởi' poll() 'và' wait() '(và gián tiếp bởi' communication() ')." Vì vậy, 'communication()' nên cẩn thận chờ quá trình kết thúc. –

1

Bạn có thể cần gọi số wait trên quy trình con của bạn và sau đó (khi đã hoàn tất), hãy kiểm tra trạng thái trong trường returncode của cá thể tiến trình con.

Tôi có một thói quen nhỏ mà các cuộc gọi thứ, có lẽ nó sẽ giúp ...

def singleProcessExecuter(command, ** kwargs): 
    assert isinstance(command, list), "Expected 'command' parameter to be a list containing the process/arguments to execute. Got %s of type %s instead" % (command, type(command)) 
    assert len(command) > 0, "Received empty list of parameters" 
    retval = { 
      "exitCode": -1, 
      "stderr": u"", 
      "stdout": u"", 
      "execTime": datetime.timedelta(0), 
      "command": None, 
      "pid": None 
      } 
    retval["command"] = command 
    log.info("::singleProcessExecuter > At %s, executing \"%s\"" % (datetime.datetime.now(), " ".join(command))) 
    #print("::singleProcessExecuter > At %s, executing \"%s\"" % (datetime.datetime.now(), " ".join(parameter))) 
    cwd = kwargs.get("cwd", os.getcwd()) 
    user = kwargs.get("user", getUid()) 
    sheel = kwargs.get("shell", False) 
    startDatetime = datetime.datetime.now() 
    myPopy = subprocess.Popen(command, cwd=cwd, preexec_fn=os.seteuid(getUid(user)), shell=sheel, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) 
    retval["pid"] = myPopy.pid 
    log.debug("::singleProcessExecuter > Command \"%s\" got pid %s" % (" ".join(command), myPopy.pid)) 
    try: 
     retval["stdout"], retval["stderr"] = myPopy.communicate() 
     myPopy.wait() 
    except OSError, osErr: 
     log.debug("::singleProcessExecuter > Got %s %s in myPopy.communicate() when trying get output of command %s. It is probably a bug (more info: http://bugs.python.org/issue1731717)" % (osErr, type(osErr), command[0])) 
    except Exception, e: 
     log.warn("::singleProcessExecuter > Got %s %s when trying to get stdout/stderr outputs of %s" % (type(e), e, " ".join(command))) 
     log.debug("::singleProcessExecuter > Got %s %s when trying to get stdout/stderr outputs of %s. Showing traceback:\n%s" % (type(e), e, " ".join(command), traceback.format_exc())) 
     raise 
    retval["exitCode"] = myPopy.returncode 
    retval["execTime"] = datetime.datetime.now() - startDatetime 
    #print(":singleProcessExecuter > This is %s's retval:\n%s" % (" ".join(parameter), retval)) 
    return retval 

Bạn có thể thử nó với:

print "This is the return: %s" % singleProcessExecuter(["ls", "-la"]) 
+0

Tôi thực sự thích mã của bạn! Tôi biết nó đã được một vài năm, nhưng tôi rất vui khi thấy các hàng nhập khẩu cần thiết cho điều đó! – schneiti

4

Quy trình không có mã trả lại cho đến khi quá trình thực thi hoàn tất. Vì vậy, nếu nó chưa hoàn thành, bạn phải quyết định những gì bạn muốn làm: chờ đợi cho nó, hoặc trả lại một số chỉ số của "Tôi chưa hoàn thành được nêu ra".

Nếu bạn muốn đợi, hãy sử dụng communicate và sau đó kiểm tra thuộc tính returncode.

Nếu bạn muốn kiểm tra xem mã trả lại có được đặt hay không và trả lại None nếu không, hãy sử dụng Popen.poll().

Các vấn đề liên quan