LoginSignup
13
10

More than 5 years have passed since last update.

pythonでweb3ライブラリを使用する。

Last updated at Posted at 2017-09-19

やったこと

pythonベースでweb3ライブラリを使うため
Web3.pyを使用する。

※Web3.pyはEthereumと対話するためのPythonライブラリ。
 Web3.js から派生したもの。

python3.4で動作を確認する。

インストール

公式からクイックスタートでインストール方法を確認する
https://web3py.readthedocs.io/en/latest/quickstart.html

$ pip3 install web3

※(追記:2017.9.21)
 上記方法でインストールする場合web3.pyのバージョンは2017年9月20日時点で3.13.5であり
 github上での最新版は3.15となっています。githubから最新版をインストールする場合は
 補足を追記していますので参考にしてください。 

実行サンプル

ためしにブロックチェーンのブロック番号を取得する。
ここでは”web3.eth.blockNumber”を使用してみる。

sample.py
from web3 import Web3,HTTPProvider

web3 = Web3(HTTPProvider('http://localhost:8545'))
blockNumber=web3.eth.blockNumber
print(blockNumber)

上記のとおり、数行ですんでしまうため、とても簡単。
簡単にethereumノードの情報を取得できてしまうので次回から使っていきたい。

その他APIについて

公式ドキュメントに記載されているので適宜確認してきたい。
https://web3py.readthedocs.io/en/latest/

補足(追記:2017/9/21)

上記ドキュメントのクイックスタートでインストールする場合
web3.pyのバージョンが最新でない場合がある。

そうした場合、公式ドキュメントにある関数の実行方法が、最新版をインストールしていないため
ドキュメントどおりに実行できない可能性がある。
(例えばweb3.sha3のコマンド指定方法がバージョン3.13から3.15で変更されているときなど
 引数の指定方法が変更されている。)

そのようなバージョンごとの変更点は、ドキュメントのリリースノートで適宜チェックしていかないといけない。
https://web3py.readthedocs.io/en/latest/releases.html#id1

web3.pyをインストールしている場合は、次のコマンドでバージョン確認できる

console
$python3 -m pip list|grep web3

(出力例)web3 (3.13.5, /home/umidachi/web3.py)

最新版をインストールするため一旦、パッケージを削除する。

console
$ pip3 uninstall web3

以下githubから最新版のセットアップ方法どおりに作業を行う。
https://github.com/pipermerriam/web3.py


$ git clone https://github.com/pipermerriam/web3.py.git
$ cd web3.py
$ virtualenv venv
$ bash venv/bin/activate

依存ライブラリはrequirements-dev.txtに定義されている。-rで一括インストールする。

$ pip3 install -r requirements-dev.txt
$ pip3 install -e .

上記作業でインストールできたか確認しとく

console
$python3 -m pip list|grep web3

(出力例) web3 (3.15.0, /home/umidachi/web3.py)

上記結果から、バージョンが最新版になれば良い。

参考

「web3.py」
https://web3py.readthedocs.io/en/latest
https://web3py.readthedocs.io/en/latest/quickstart.html

13
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10