这里使用最为方便的pip命令来安装
pip install web3
如果在安装过程中遇到图中错误,可以使用以下命令解决
sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libevent-dev
简单的测试
>>> from web3 import Web3, HTTPProvider, IPCProvider
# 基于HTTP方式建立连接
>>> web3 = Web3(HTTPProvider('http://localhost:8545'))
# 或者以IPC方式创建连接
>>> web3 = Web3(IPCProvider())
>>> web3.eth.blockNumber
4000000
使用pip安装py-solc编译合约
pip install py-solc
和一个简单的合约进行交互
import json
import web3
from web3 import Web3, HTTPProvider, IPCProvider
from solc import compile_source
from web3.contract import ConciseContract
# Solidity source code
contract_source_code = '''
pragma solidity ^0.4.21;
contract Greeter {
string public greeting;
function Greeter() public {
greeting = 'Hello';
}
function setGreeting(string _greeting) public {
greeting = _greeting;
}
function greet() view public returns (string) {
return greeting;
}
}
'''
compiled_sol = compile_source(contract_source_code) # Compiled source code
contract_interface = compiled_sol['<stdin>:Greeter']
# web3.py instance
w3 = Web3(HTTPProvider('http://localhost:8545'))
# set pre-funded account as sender
w3.eth.defaultAccount = w3.eth.accounts[0]
# Instantiate and deploy contract
Greeter = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
# Submit the transaction that deploys the contract
tx_hash = Greeter.constructor().transact()
# Wait for the transaction to be mined, and get the transaction receipt
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
# Create the contract instance with the newly-deployed address
greeter = w3.eth.contract(
address=tx_receipt.contractAddress,
abi=contract_interface['abi'],
)
# Display the default greeting from the contract
print('Default contract greeting: {}'.format(
greeter.functions.greet().call()
))
print('Setting the greeting to Nihao...')
tx_hash = greeter.functions.setGreeting('Nihao').transact()
# Wait for transaction to be mined...
w3.eth.waitForTransactionReceipt(tx_hash)
# Display the new greeting value
print('Updated contract greeting: {}'.format(
greeter.functions.greet().call()
))
# When issuing a lot of reads, try this more concise reader:
reader = ConciseContract(greeter)
assert reader.greet() == "Nihao"
注意,如果进行简单的合约测试,需要安装testrpc或使用geth的私有链。这里使用http进行连接。
w3 = Web3(HTTPProvider('http://localhost:8545')))
网友评论