IT Share you

Fabric을 사용하여 원격 쉘에서 run () 호출을 할 때 오류 코드를 포착 할 수 있습니까?

shareyou 2020. 11. 20. 17:16
반응형

Fabric을 사용하여 원격 쉘에서 run () 호출을 할 때 오류 코드를 포착 할 수 있습니까?


일반적으로 Fabric은 run () 호출이 0이 아닌 종료 코드를 반환하는 즉시 종료됩니다. 그러나 일부 통화의 경우 이는 예상됩니다. 예를 들어 PNGOut은 파일을 압축 할 수없는 경우 오류 코드 2를 반환합니다.

현재는 쉘 로직 ( do_something_that_fails || true또는 do_something_that_fails || do_something_else)을 사용하여이 제한을 피할 수 있지만, 내 로직을 일반 Python으로 유지할 수 있습니다 (Fabric 약속처럼).

Fabric이 패닉 상태로 죽지 않고 오류 코드를 확인하고 이에 대응하는 방법이 있습니까? 나는 여전히 다른 호출에 대한 기본 동작을 원하기 때문에 환경을 수정하여 동작을 변경하는 것은 좋은 선택이 아닌 것 같습니다 (그리고 제가 기억하는 한, 당신은 어쨌든 죽는 대신 경고하도록 지시하는 데 사용할 수 있습니다).


settings컨텍스트 관리자와 warn_only설정 을 사용하여 0이 아닌 종료 코드에 대한 중단을 방지 할 수 있습니다 .

from fabric.api import settings

with settings(warn_only=True):
    result = run('pngout old.png new.png')
    if result.return_code == 0: 
        do something
    elif result.return_code == 2: 
        do something else 
    else: #print error to user
        print result
        raise SystemExit()

업데이트 : 내 대답이 오래되었습니다. 아래 설명을 참조하십시오.


그래 넌 할수있어. 환경의 abort_exception. 예를 들면 :

from fabric.api import settings

class FabricException(Exception):
    pass

with settings(abort_exception = FabricException):
    try:
        run(<something that might fail>)
    except FabricException:
        <handle the exception>

에 대한 문서 abort_exception여기에 있습니다 .


분명히 환경을 망치 것이 답입니다.

fabric.api.settings컨텍스트 관리자 (와 함께 with)로 사용하여 개별 문에 적용 할 수 있습니다. run(), local()sudo()호출 의 반환 값은 셸 명령의 출력 일뿐만 아니라 오류에 대응할 수있는 특수 속성 ( return_codefailed)도 있습니다.

나는 subprocess.Popen파이썬의 일반적인 예외 처리의 동작 이나 더 가까운 것을 찾고 있었던 것 같습니다 .


이 시도

from fabric.api import run, env
env.warn_only = True # if you want to ignore exceptions and handle them yurself

command = "your command"
x = run(command, capture=True) # run or local or sudo
if(x.stderr != ""):
    error = "On %s: %s" %(command, x.stderr)
    print error
    print x.return_code # which may be 1 or 2
    # do what you want or
    raise Exception(error) #optional
else:
    print "the output of %s is: %s" %(command, x)
    print x.return_code # which is 0

참고 URL : https://stackoverflow.com/questions/4888568/can-i-catch-error-codes-when-using-fabric-to-run-calls-in-a-remote-shell

반응형