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

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

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

    bitcoin sendtoaddress <bitcoin address> <amount>


    So for example:

    bitcoin sendtoaddress 1HoCUcbK9RbVnuaGQwiyaJGGAG6xrTPC9y 1.4214


    If it is successful I get a transaction id as output, but if I try to transfer an amount larger than my bitcoin balance, I get the following output:

    error: {"code":-4,"message":"Insufficient funds"}


    In my Python program I now try to do the payment as follows:

    import subprocess

    try:
    output = subprocess.check_output(['bitcoin', 'sendtoaddress', address, str(amount)])
    except:
    print "Unexpected error:", sys.exc_info()


    If there's enough balance it works fine, but if there's not enough balance sys.exc_info() prints out this:

    (<class 'subprocess.CalledProcessError'>, CalledProcessError(), <traceback object at 0x7f339599ac68>)


    It doesn't include the error which I get on the command line though. So my question is; how can I get the outputted error ({"code":-4,"message":"Insufficient funds"}) from within Python?

    Continue reading...

Compartilhe esta Página