以太坊作为全球领先的智能合约平台,其强大的功能和开放性吸引了无数开发者和企业,而Python,以其简洁的语法、丰富的库生态和易用性,成为了众多开发者的首选语言,将Python与以太坊结合,我们可以轻松地与以太坊区块链进行交互,例如查询账户余额、发送交易、部署智能合约、调用合约方法等,本文将详细介绍如何使用Python调用以太坊,涵盖环境搭建、常用库介绍及核心功能实践。
在开始之前,我们需要准备以下环境和工具:
geth(Go-Ethereum)或Parity等客户端在自己的机器上运行一个全节点或轻节点,这提供了更高的隐私性和控制权,但需要更多的硬件资源和同步时间。pip install web3Web3.py是Python调用以太坊的基石,它封装了以太坊的各种功能,使得开发者可以用Python代码实现区块链操作。

连接节点:首先需要创建一个Web3实例,并连接到以太坊节点。
连接到Infura:
from web3 import Web3 # 替换为你的Infura项目ID infura_url = "https://mainnet.infura.io/v3/YOUR_PROJECT_ID" w3 = Web3(Web3.HTTPProvider(infura_url))
连接到本地节点(如geth默认端口8545):
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545")) 检查连接:

print(w3.isConnected()) # 应该返回True print(w3.eth.blockNumber) # 打印当前区块号,测试连接是否正常
# 替换为你要查询的以太坊地址
address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e"
balance_wei = w3.eth.get_balance(address)
balance_eth = w3.from_wei(balance_wei, 'ether')
print(f"地址 {address} 的余额是: {balance_eth} ETH") 发送交易是相对复杂的操作,需要构造交易对象并进行签名。
构造并发送交易(以发送ETH为例):
# 发送方账户(需要私钥签名,注意安全!)
sender_address = "0xYourSenderAddress"
sender_private_key = "YOUR_PRIVATE_KEY" # 务必妥善保管,不要泄露!
# 接收方地址
receiver_address = "0xReceiverAddress"
# 获取nonce(每个账户发送交易的序号,防止重放攻击)
nonce = w3.eth.get_transaction_count(sender_address)
# 构造交易
transaction = {
'nonce': nonce,
'to': receiver_address,
'value': w3.to_wei(0.1, 'ether'), # 发送0.1 ETH
'gas': 200000, # Gas限制
'gasPrice': w3.eth.gas_price, # Gas价格
'chainId': 1 # 主网chainId,测试网请使用对应的chainId(如Goerli是5)
}
# 签名交易
signed_txn = w3.eth.account.sign_transaction(transaction, sender_private_key)
# 发送交易
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
# 等待交易被打包
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(f"交易已发送,交易哈希: {tx_hash.hex()}")
print(f"交易回执: {tx_receipt}") 注意:私钥极度敏感,切勿硬编码在代码中或提交到版本控制系统,建议使用环境变量或专门的密钥管理工具。
智能合约是以太坊的核心,Python通过Web3.py可以方便地部署和调用合约。

编译智能合约: 在使用Python之前,你需要先使用Solidity语言编写智能合约,并编译成ABI(application Binary Interface)和字节码(Bytecode),可以使用solc(Solidity编译器)或在线编译器(如Remix IDE)。 假设我们有一个简单的SimpleStorage.sol合约,编译后得到:
abi: 合约的接口描述(JSON格式)bytecode: 部署合约的字节码部署智能合约:
# 假设你已经有了abi和bytecode
# simple_storage_abi = [...] # 这里填入你的合约ABI
# simple_storage_bytecode = "0x..." # 这里填入你的合约字节码
# 部署者账户和私钥
deployer_address = "0xYourDeployerAddress"
deployer_private_key = "YOUR_DEPLOYER_PRIVATE_KEY"
nonce = w3.eth.get_transaction_count(deployer_address)
# 构造部署交易
contract = w3.eth.contract(abi=simple_storage_abi, bytecode=simple_storage_bytecode)
construct_txn = contract.constructor().buildTransaction({
'nonce': nonce,
'gas': 2000000,
'gasPrice': w3.eth.gas_price,
'chainId': 1
})
# 签名并发送
signed_txn = w3.eth.account.sign_transaction(construct_txn, deployer_private_key)
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
# 获取已部署的合约实例
contract_address = tx_receipt['contractAddress']
simple_storage_contract = w3.eth.contract(address=contract_address, abi=simple_storage_abi)
print(f"合约已部署,地址: {contract_address}") 调用合约读方法(Constant Functions): 调用不会修改区块链状态的方法,不需要发送交易,直接调用即可。
# 假设合约有一个名为 'get' 的getter方法
# 调用get方法
current_value = simple_storage_contract.functions.get().call()
print(f"当前存储的值是: {current_value}") 调用合约写方法(Non-constant Functions): 调用会修改区块链状态的方法,需要像发送普通交易一样构造并发送交易。
# 假设合约有一个名为 'set' 的setter方法,接受一个uint256参数
value_to_set = 42
nonce = w3.eth.get_transaction_count(deployer_address)
set_txn = simple_storage_contract.functions.set(value_to_set).buildTransaction({
'nonce': nonce,
'gas': 200000,
'gasPrice': w3.eth.gas_price,
'chainId': 1
})
signed_set_txn = w3.eth.account.sign_transaction(set_txn, deployer_private_key)
tx_hash_set = w3.eth.send_raw_transaction(signed_set_txn.rawTransaction)
tx_receipt_set = w3.eth.wait_for_transaction_receipt(tx_hash_set)
print(f"设置值的交易已发送,哈希: {tx_hash_set.hex()}")
# 再次调用get方法验证
updated_value = simple_storage_contract.functions.get().call()
print(f"更新后的存储值是: {updated_value}") 除了Web3.py,还有一些其他库可以简化特定操作或提供额外功能:
免责声明:本文为转载,非本网原创内容,不代表本网观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
如有疑问请发送邮件至:bangqikeconnect@gmail.com