如何使用python web3
时间: 2024-06-05 12:01:48 浏览: 16
Python Web3是一个用于与以太坊区块链进行交互的Python库。以下是一个简单的使用Python Web3库的例子:
1. 首先,确保已经安装了Python Web3库。可以使用以下命令进行安装:
```
pip install web3
```
2. 导入Web3库并连接到以太坊区块链
```python
from web3 import Web3
# 连接到以太坊主网
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/your-project-id'))
# 打印当前块高度
print(w3.eth.blockNumber)
```
3. 发送一笔交易
```python
# 定义发送方和接收方地址
sender_address = '0x...'
receiver_address = '0x...'
# 构造交易字典
transaction = {
'from': sender_address,
'to': receiver_address,
'value': w3.toWei(1, 'ether'),
'gas': 200000,
'gasPrice': w3.toWei('50', 'gwei')
}
# 发送交易并获取交易哈希
tx_hash = w3.eth.sendTransaction(transaction)
# 打印交易哈希
print(tx_hash.hex())
```
这只是一个简单的例子,Python Web3库还提供了很多其他的功能,如查询以太坊账户余额、部署智能合约等。更多信息可以参考Web3官方文档。