카테고리 없음

[파이썬] check_output에서 예외 출력을 보는 방법

행복을전해요 2021. 2. 16. 21:32

설정하고 subprocess.CalledProcessError.message. 이렇게하면 오류가 처리되지 않을 때 메시지가 표시되고 다른 프로그래머가이 예외를 사용할 가능성이있는 경우 좋은 프로그래밍입니다.

-------------------

문서에는 실제로 이에 대한 예가stderr=subprocess.STDOUT 있습니다. 호출에서 사용 합니다.

또한 subprocess.CalledProcessError에는 프로세스의 output출력을 포함 하는 속성이 있음을 언급합니다 (나는 이것이라고 가정 stdout하지만 아마도 호출 자체에서 stderr설정할 필요가없는 경우 stderr).

따라서 다음을 사용할 수 있어야합니다 (예상되지 않음).

try:
    output = subprocess.check_output('command ' + machineName)
        for line in output.split('\n'):
                if 'TextToSearchFor' in line:
                            return line
                            except subprocess.CalledProcessError:
                                print subprocess.CalledProcessError.output
                                    return "Error"
                                    return
                                    
-------------------

예외를 사용할 수 있습니다.

def myFunction(machineName):
    try:
            output = subprocess.check_output('command ' + machineName)
                    for line in output.split('\n'):
                                if 'TextToSearchFor' in line:
                                                return line
                                                    except Exception, e:
                                                            print e
                                                                    return "Error"
                                                                        return
                                                                        

스택 추적에 관심이있는 경우 다음을 수행 할 수 있습니다.

import trace

예외를 제외하고 e : 추가 할 수 있습니다.

traceback.print_exc()
-------------------

주의하십시오-트래핑하는 예외가 예상 할 수있는 유일한 예외는 아닙니다.

>>> import subprocess
>>> try:
...     output = subprocess.check_output("nosuch")
... except Exception as e:
...     print str(e)
...
[Errno 2] No such file or directory
>>> e
OSError(2, 'No such file or directory')
>>> type(e)
<type 'exceptions.OSError'>

또한 함수에 대한 인터페이스는 모든 호출이 다음과 같아야하므로 오류에 대한 특정 검사를 수행해야하므로 논리의 명확성이 떨어집니다.

result = myFunction(someArg):
if result.startswith("error"):
    # handle issue somehow
    else:
        # normal logic flow to do something with result
        

함수에서 오류 검사를 제거하고 호출시 결과 예외를 처리하여 적절한 지점에서 예외를 처리하는 것이 실제로 훨씬 간단합니다. 코드는 다음과 같습니다.

try:
    # normal logic flow to do something with result
    except (tuple, of, exceptions) as e:
        # handle issue somehow
        

또한 예외를 dtrings로 변환 할 수 있으며, 이는 시작 예제에 표시된대로 일반적으로 연관된 오류 메시지를 제공하므로 이것이 귀하의 질문에 대한 실제 대답입니다.

Python이 최신 버전이라면 변경없이 Python 3으로 마이그레이션하기 except ... as name:보다는 형식을 사용해야합니다 except ..., name:.



출처
https://stackoverflow.com/questions/22079796