The Monero team recently added a tool that makes it easy to integrate Monero RPC with Python. It can connect to running daemon and wallet and exposes their RPC interfaces:
The following command will connect to a monerod running on mainnet on default settings:
utils/python-rpc/console 18081
You'll get this output:
Variable 'daemon' connected to daemon RPC on 127.0.0.1:18081
>>>
You're now in a python interpreter, and the daemon
variable is set to an object which can call daemon RPC directly, eg:
>>> daemon.get_version()
{u'status': u'OK', u'untrusted': False, u'version': 131078}
>>>
For the use case above (retrieving 21 nonce values from the blockchain from height 1000):
>>> [x.nonce for x in daemon.getblockheadersrange(1000, 1020).headers]
[3419004817, 3320605335, 295465941, 3696734864, 2221411748, 2201153093, 148086550, 524920481, 1766174771, 1831485859, 2409397405, 804573540, 535538542, 1487558207, 3340140970, 4029873826, 3890252333, 586366003, 1681558754, 1323530723, 240084243]
>>>
You can also connect the console to several processes, daemon and wallet, so you can interact with both from the same interpreter. The console will detect whether it's connecting to a node or a wallet, and will create the RPC proxy objects as daemon
or wallet
accordingly. If you connect to more than one demon or more than one wallet, the RPC objects will be daemons
and/or wallets
arrays instead of single variables. For instance, if you have a wallet running on port 8080:
$ utils/python-rpc/console 18081 8080
Variable 'daemon' connected to daemon RPC on 127.0.0.1:18081
Variable 'wallet' connected to wallet RPC on 127.0.0.1:8080
>>>
The console tool accepts full URLs if the daemon/wallet does not run on 127.0.0.1.
To use that framework in other Python programs, you should import the module(s) you need:
from framework.daemon import Daemon
from framework.wallet import Wallet