본문 바로가기
파이썬

파이썬 "subprocess.Popen"-성공 및 오류 확인

by º기록 2020. 12. 11.
반응형

하위 프로세스가 성공적으로 실행되었는지 실패했는지 확인하고 싶습니다. 현재 나는 해결책을 찾았지만 그것이 정확하고 신뢰할 수 있는지 확실하지 않습니다. 모든 프로세스가 stdout 에 대해 정중하게 stderr에만 오류를 출력한다는 것이 보장됩니까?

참고 : 출력을 리디렉션 / 인쇄하는 데 관심이 없습니다. 나는 이미 방법을 알고 있습니다.

pipe = subprocess.Popen(command,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True)

if "" == pipe.stdout.readline():
    print("Success")
    self.isCommandExectutionSuccessful = True

if not "" == pipe.stderr.readline():
    print("Error")
    self.isCommandExectutionSuccessful = True

또는 :

   if "" == pipe.stdout.readline():
       print("Success")
       self.isCommandExectutionSuccessful = True
   else:
       print("Error")
       self.isCommandExectutionSuccessful = False

과:

   if not "" == pipe.stderr.readline():
       print("Success")
       self.isCommandExectutionSuccessful = True
   else:
       print("Error")
       self.isCommandExectutionSuccessful = False

 

해결 방법

 

프로세스의 결과물로 무엇을해야합니까?


그런 다음이를 다음과 같이 사용할 수 있습니다.

try:
  subprocess.check_call(command)
except subprocess.CalledProcessError:
  # There was an error - command exited with non-zero code

그러나 이는 성공적인 완료를 위해 종료 코드 0을 반환하고 오류에 대해 0이 아닌 값을 반환하는 command 에 의존합니다.

출력도 캡처해야하는 경우 check_output 메서드가 더 적절할 수 있습니다. 필요한 경우에도 표준 오류를 리디렉션 할 수 있습니다.

try:
  proc = subprocess.check_output(command, stderr=subprocess.STDOUT)
  # do something with output
except subprocess.CalledProcessError:
  # There was an error - command exited with non-zero code


 

참조 페이지 https://stackoverflow.com/questions/25079140

 

 

반응형

댓글