Interact with Ethereum using Python

Last modified: 2023-03-20

Blockchain Web3


To use “py-solc”, the Ethereum and Solidity are required in our system. So if you don’t have them yet, install them.

sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc

Install Python Packages

pip3 install py-solc
pip3 install web3

Compile Contract

import solc

with open('MyContract.sol', 'r') as f:
	contract_source_code =

compiled_sol = solc.compile_source(contract_source_code)

contract_bytecode = compiled_sol['<stdin>:MyContract']['bin']
contract_abi = compiled_sol['<stdin>:MyContract']['abi']

Interact with Ethereum Chain

Create the Python script using web3 to interact with blockchain.

from web3 import Web3

rpc_url = ""
private_key = "0x1234..."
addr = "0x1234..."
contract_addr = "0x1234..."

# Connect
w3 = Web3(Web3.HTTPProvider(rpc_url))

# Get the latest block

# Get the balance of specified address
balance = w3.eth.get_balance(addr)
print(f"Balance is {balance}")