如何从 Python subprocess.check_output() 捕获异常输出?
问题描述
我正在尝试从 Python 中进行比特币支付.在 bash 中,我通常会这样做:
I'm trying to do a Bitcoin payment from within Python. In bash I would normally do this:
bitcoin sendtoaddress <bitcoin address> <amount>
例如:
bitcoin sendtoaddress 1HoCUcbK9RbVnuaGQwiyaJGGAG6xrTPC9y 1.4214
如果成功,我会得到一个交易 ID 作为输出,但如果我尝试转移一个大于我的比特币余额的金额,我会得到以下输出:
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"}
在我的 Python 程序中,我现在尝试按如下方式付款:
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()
如果有足够的余额,它可以正常工作,但如果没有足够的余额,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>)
它不包括我在命令行上遇到的错误.所以我的问题是;如何从 Python 中获取输出的错误({code":-4,message":Insufficient fund"}
)?
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?
解决方案
根据subprocess.check_output()
docs,错误引发的异常有一个 output
属性,可用于访问错误详细信息:
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)
然后您应该能够分析此字符串并使用 json
模块解析错误详细信息:
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'])
相关文章