How to catch exception output from Python subprocess.check_output()?

后端 未结 7 1169
灰色年华
灰色年华 2020-11-29 00:35

I\'m trying to do a Bitcoin payment from within Python. In bash I would normally do this:

bitcoin sendtoaddress  
         


        
7条回答
  •  生来不讨喜
    2020-11-29 01:01

    As mentioned by @Sebastian the default solution should aim to use run(): https://docs.python.org/3/library/subprocess.html#subprocess.run

    Here a convenient implementation (feel free to change the log class with print statements or what ever other logging functionality you are using):

    import subprocess
    
    def _run_command(command):
        log.debug("Command: {}".format(command))
        result = subprocess.run(command, shell=True, capture_output=True)
        if result.stderr:
            raise subprocess.CalledProcessError(
                    returncode = result.returncode,
                    cmd = result.args,
                    stderr = result.stderr
                    )
        if result.stdout:
            log.debug("Command Result: {}".format(result.stdout.decode('utf-8')))
        return result
    

    And sample usage (code is unrelated, but I think it serves as example of how readable and easy to work with errors it is with this simple implementation):

    try:
        # Unlock PIN Card
        _run_command(
            "sudo qmicli --device=/dev/cdc-wdm0 -p --uim-verify-pin=PIN1,{}"
            .format(pin)
        )
    
    except subprocess.CalledProcessError as error:
        if "couldn't verify PIN" in error.stderr.decode("utf-8"):
            log.error(
                    "SIM card could not be unlocked. "
                    "Either the PIN is wrong or the card is not properly connected. "
                    "Resetting module..."
                    )
            _reset_4g_hat()
            return
    

提交回复
热议问题