這里使用最為方便的pip命令來安裝
pip install web3
如果在安裝過程中遇到圖中錯(cuò)誤驹止,可以使用以下命令解決
sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libevent-dev
簡(jiǎn)單的測(cè)試
>>> from web3 import Web3, HTTPProvider, IPCProvider
# 基于HTTP方式建立連接
>>> web3 = Web3(HTTPProvider('http://localhost:8545'))
# 或者以IPC方式創(chuàng)建連接
>>> web3 = Web3(IPCProvider())
>>> web3.eth.blockNumber
4000000
使用pip安裝py-solc編譯合約
pip install py-solc
和一個(gè)簡(jiǎn)單的合約進(jìn)行交互
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"
注意,如果進(jìn)行簡(jiǎn)單的合約測(cè)試胳螟,需要安裝testrpc或使用geth的私有鏈。這里使用http進(jìn)行連接。
w3 = Web3(HTTPProvider('http://localhost:8545')))