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

后端 未结 7 1165
灰色年华
灰色年华 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:26

    According to the subprocess.check_output() docs, the exception raised on error has an output attribute that you can use to access the error details:

    try:
        subprocess.check_output(...)
    except subprocess.CalledProcessError as e:
        print(e.output)
    

    You should then be able to analyse this string and parse the error details with the json module:

    if e.output.startswith('error: {'):
        error = json.loads(e.output[7:]) # Skip "error: "
        print(error['code'])
        print(error['message'])
    

提交回复
热议问题