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

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

    I don't think the accepted solution handles the case where the error text is reported on stderr. From my testing the exception's output attribute did not contain the results from stderr and the docs warn against using stderr=PIPE in check_output(). Instead, I would suggest one small improvement to J.F Sebastian's solution by adding stderr support. We are, after all, trying to handle errors and stderr is where they are often reported.

    from subprocess import Popen, PIPE
    
    p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE, stderr=PIPE)
    output, error = p.communicate()
    if p.returncode != 0: 
       print("bitcoin failed %d %s %s" % (p.returncode, output, error))
    

提交回复
热议问题