How to connect to bitcoin core over rpc with python3?
One of the ways to interact with Bitcoin Core is through its Remote Procedure Call (RPC) interface, which allows external programs to send commands to a running Bitcoin Core instance and receive responses. By using Bitcoin Core over RPC with Python3 you are able to have greater control and flexibility over the custom parameters you set and performance.
Below are the the steps to follow in order to connect Bitcoin Core over RPC with Python3.
Bitcoin Core Config file
Enable the RPC server in your Bitcoin Core instance by adding the following lines to your bitcoin.conf file (located in your Bitcoin Core data directory):
rpcuser=yourusername
rpcpassword=yourpassword
rpcbind=127.0.0.1
rpcallowip=127.0.0.1
rpcport=8332
server=1
Make sure to replace yourusername
and yourpassword
with your desired username and password
Install bitcoinrpc library
Using the pip command install the bitcoinrpc
library:
pip install python-bitcoinrpc
Create new Python script and import the necessary bitcoin modules:
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
Create a connection to the RPC server using the AuthServiceProxy
class:
rpc_user = 'yourusername'
rpc_password = 'yourpassword'
rpc_port = 8332
rpc_connection = AuthServiceProxy(f'http://{rpc_user}:{rpc_password}@localhost:{rpc_port}')
Make sure to replace yourusername
and yourpassword
with your username and password, and rpc_port
with the port number you specified in your bitcoin.conf
file.
Bitcoin RPC python command
You are not ready to make rpc calls using the rpc_connection
object.
For example, to get the current block count, you can use the getblockcount
method:
block_count = rpc_connection.getblockcount()
print(f'Current block count: {block_count}')
The above will respond with a block count in your console.
If you need to to your other Bitcoin RPC commands then check out guide on bitcoin RPCs