如何捕捉Python的subprocess.check_output异常输出()? [英] How to catch exception output from 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>
因此,例如:
so for example:
bitcoin sendtoaddress 1HoCUcbK9RbVnuaGQwiyaJGGAG6xrTPC9y 1.4214
如果是全成我得到的事务id作为输出,但如果我尝试比我的比特币余额转移的量时,我得到以下的输出:
if it is successfull 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
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?
所有的提示是欢迎!
推荐答案
按照<一个href=\"https://docs.python.org/2/library/subprocess.html#subprocess.check_output\"><$c$c>subprocess.check_output()$c$c>文档上的错误引发的异常有一个输出
属性,你可以用它来访问错误的详细信息:
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']
这篇关于如何捕捉Python的subprocess.check_output异常输出()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!