Bitcoin & Blockchain Programming #007 – RPCs via Python

by Albert Szmigielski

Previously we issued commands to bitcoind via PHP using Remote Procedure Calls. In today’s tutorial we will do the same using Python. We are assuming you have python installed on your machine. On Ubuntu 14.0.4 Python 3.4 is installed by default. If you do not have Python installed, just do a search on how to do it, there is a number of good tutorials out there. Or depending on your system you can try

If you are not sure if Python is installed on your system you can check by doing:

for versions 2.x or

for versions 3.x

The RPCs to bitcoind are accomplished via json format, so we will need a library for that. Jeff Garzik has a library just for that purpose. To get it:

We need to create an object to connect to bitcoind, as arguments AuthServiceProxy requires a username, a password and the IP where the wallet is running. The user name and password are the credentials you specified in the bitcoin.conf file for rpcuser and rpcpassword. The IP is the IP of the machine where bitcoind is running if you are running it on your own machine it will be 127.0.0.1. We will also need the port number, which in case of testnet is 18322.

In our case our credentials are:

the format is as follows:

Putting it all together we have:

You can already see that this is very similar to what we did in PHP in our last tutorial.

Lets’s simply ask bitcoind for the block count. We could do something like the following:

and then just print it out:

As you can see the call access.getblockcount() makes the RPC to bitcoind and returns the information in the variable we assign it to (in our case blkcount). We can issue any bitcoind command like that.

We of course need to let python know about the library we are using:

Let’s put it all together.

We can try other commands, let’s do getinfo

and then print it just one piece of information say, the version

or we can iterate through the array and print it all out

Putting it all in a file:

Now, let’s run it

Screenshot - 16-02-28 - 09:22:50 PM

So there we have it. We can now connect to bitcoind programmatically, issue commands and receive information back. This will allow us to build more complex and sophisticated problems in the future.
Remember to see all the different bitcoind commands that are available just issue the following command (make sure bitcoind is running in the background)

Leave a Reply

Your email address will not be published. Required fields are marked *