SlideShare ist ein Scribd-Unternehmen logo
1 von 35
ひのきのぼうだけで
             全クリを目指す
        kyoto.py Python勉強会 in 高槻



@a rom a_bl ack (t ty170)
お前誰よ?
名前 : aroma_black

 最近tty170とかも使ってる

所属 : 某SIerのSE兼PG

 主に技術的課題解決要員

Pythonはシェルスクリプト覚えるのが嫌で
使い始めました
お断り



今日はPython2.7のはなしです

Python3.x? なにそれおいしいの?
装備品の紹介


ひのきのぼう

標準ライブラリ
http://www.python.jp/doc/release/library/
Pythonの標準ライブラリ


batteries included(電池付属)という哲学で
作られた
http://www.python.org/dev/peps/pep-0206/

すぐに使える強力(?)かつ多彩なライブラリ
Stage 1


敵全体攻撃

コレクションクラスを操作してみる

プログラミングの基本
itertools
  いっぱいあるのでドキュメントを参照

    イテレータやジェネレータを返すので
    リスト内包表記を組み合わせて使うと
    少ない行数で書ける

>>> from itertools import ifilter
>>> foobar = ['1', '2', 'foo', '4', 'bar']
>>> [e for e in ifilter(lambda x: x.isdigit(), foobar)]
['1', '2', '4']
Stage 2

仲間を増やす

シェルスクリプト的なものを作ってみる
(その時にあると便利なもの)

引数の解析って面倒臭いよね
argparse
    コマンドラインオプションの解析器

    optperseの後継
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)
argparse
実行結果
  $ prog.py -h
  usage: prog.py [-h] [--sum] N [N ...]

  Process some integers.

  positional arguments:
   N           an integer for the accumulator

  optional arguments:
   -h, --help show this help message and exit
   --sum       sum the integers (default: find the
  max)
Stage 3



てきをあやつる

Pythonからファイル操作を簡単に行う
shutil
いっぱいあるのでドキュメント参照

ファイル操作はos, os.pathモジュールも
よく使います
 import os, shutil

 for root, dirs, files in os.walk(‘.’):
     for filename in files:
         if filename.endswith(‘.py’):
             pyfile = os.path.join(root, filename)
             shutil.copyfile(pyfile, “./pyfiles”)
Stage 4


強敵エクセルのおともだち、CSV

CSVファイルの読み書き

仕事でよく使うよね?
csvパッケージ
読み込み   import csv
       with open('some.csv', 'rb') as f:
           reader = csv.reader(f)
           for row in reader:
               print row

書き込み
       import csv
       with open('some.csv', 'wb') as f:
           writer = csv.writer(f)
           writer.writerows(someiterable)




すこし弄ればTSVとかも読めます
Stage 5



酒場で情報収集

Webスクレイピング
urllib2
   HTMLソースを取得するコードを3行で頼む

>>> import urllib2
>>> f = urllib2.urlopen('http://www.python.org/')
>>> print f.read(100)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//
EN">
<?xml-stylesheet href="./css/ht2html
Stage 6

試練の時

xUnit系のパッケージ付属

ドキュメントにテスト可能なコードも書ける
簡易的なdoctestというモジュールもある
unittest
xUnit系のテスティングモジュール
 import random
 import unittest

 class TestSequenceFunctions(unittest.TestCase):

     def setUp(self):
         self.seq = range(10)

     def test_sample(self):
         with self.assertRaises(ValueError):
             random.sample(self.seq, 20)
         for element in random.sample(self.seq, 5):
             self.assertTrue(element in self.seq)

 if __name__ == '__main__':
     unittest.main()
unittest
さっきのテストの実行結果


 .
 -------------------------------------------------------
 ---------------
 Ran 1 tests in 0.000s

 OK
doctest
対話シェルのコードを貼付けるだけ

docstringにも埋め込める
    def add(n, m):
        """Return n + m.

        >>> add(1, 2)
        3
        """
        return n + m

    if __name__ == "__main__":
        import doctest
        doctest.testmod()
doctest
異常が無ければ何も表示されない

異常があったときはエラーが表示される
 ***************************************************
 File "add.py", line 6, in __main__.add
 Failed example:
      add(1, 2)
 Expected:
      4
 Got:
      3
 ***************************************************
 1 items had failures:
    1 of    1 in __main__.add
 ***Test Failed*** 1 failures.
Stage Ex


エイリアンと戦う

関数言語的な機能を使ってみる

関数型言語使ってみたいけど敷居高そう...
functools
関数の部分適用
  >>> from functools import partial
  >>> basetwo = partial(int, base=2)
  >>> basetwo.__doc__ = 'Convert base 2 string to
  an int.'
  >>> basetwo('10010')
  18




応用すればカリー化とかもできる...はず
クリアできないとき....



そんな時は先人達の知恵をかりましょう。
つよくてニューゲーム

標準ライブラリだけでクリアする
と言ったなあれは嘘だ

PyPIと呼ばれるパッケージ管理サイト
http://pypi.python.org/pypi

RubyのRubyGems, PerlのCPANに相当
パッケージ管理ツールpip

パッケージを自動でインストールしてくれる
優れもの

easy_install は衰退しました

Python3対応
installing pip

前準備としてdistributeをインストール
http://python-distribute.org/distribute_setup.py

pipをダウンロード
http://pypi.python.org/pypi/pip/

展開してディレクトリの中で
$python setup.py install
pipの基本的な使い方
パッケージのインストール

  pip install package_name
パッケージのアンインストール

  pip uninstall package_name
パッケージの検索

  pip search package_name
http://www.pip-installer.org/en/latest/index.html
virtualenv


仮想的な実行環境を作る為のツール

アプリケーション間で依存するパッケージの
のバージョンの分離とか
virtualenvの基本的な使い方



PyPIにドキュメントがあるのでどうぞ!
http://pypi.python.org/pypi/virtualenv
virtualenv wrapper


virtualenvをシェルで使いやすくする為のツール
http://pypi.python.org/pypi/virtualenvwrapper/

Windowsな人はvirtualenv-win
https://github.com/davidmarble/virtualenvwrapper-win/
virtualenv wrapperの(ry



さっきのPyPIのサイトをどうぞ!
それでも倒せない



レベルを上げて物理で殴ればいい

たまには人に聞くなどもしてみては?
まとめ
Pythonの標準ライブラリは強力

 きんのひのきのぼう

今日紹介したPython標準ライブラリは一部です

 スイスの十得ナイフと言われているらしい

 ドキュメント眺めると新たな発見がある
 かも?
ご清聴ありがとうございました

Weitere ähnliche Inhalte

Was ist angesagt?

シェル芸初心者によるシェル芸入門
シェル芸初心者によるシェル芸入門シェル芸初心者によるシェル芸入門
シェル芸初心者によるシェル芸入門
icchy
 
Lisp tutorial for Pythonista : Day 1
Lisp tutorial for Pythonista : Day 1Lisp tutorial for Pythonista : Day 1
Lisp tutorial for Pythonista : Day 1
Ransui Iso
 

Was ist angesagt? (20)

シェル入門
シェル入門シェル入門
シェル入門
 
Sounds Like Common Lisp - ゼロからはじめるサウンドプログラミング
Sounds Like Common Lisp - ゼロからはじめるサウンドプログラミングSounds Like Common Lisp - ゼロからはじめるサウンドプログラミング
Sounds Like Common Lisp - ゼロからはじめるサウンドプログラミング
 
PostgreSQLとpython
PostgreSQLとpythonPostgreSQLとpython
PostgreSQLとpython
 
Good Parts of PHP and the UNIX Philosophy
Good Parts of PHP and the UNIX PhilosophyGood Parts of PHP and the UNIX Philosophy
Good Parts of PHP and the UNIX Philosophy
 
明日から使える気になるGo言語による並行処理
明日から使える気になるGo言語による並行処理明日から使える気になるGo言語による並行処理
明日から使える気になるGo言語による並行処理
 
仕事で使えるシェルスクリプト
仕事で使えるシェルスクリプト仕事で使えるシェルスクリプト
仕事で使えるシェルスクリプト
 
Introduction of Python
Introduction of PythonIntroduction of Python
Introduction of Python
 
RuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityRuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for Unity
 
3分でサーバオペレーションコマンドを作る技術
3分でサーバオペレーションコマンドを作る技術3分でサーバオペレーションコマンドを作る技術
3分でサーバオペレーションコマンドを作る技術
 
Google Developer Day 2010 Japan: プログラミング言語 Go (鵜飼 文敏)
Google Developer Day 2010 Japan: プログラミング言語 Go (鵜飼 文敏)Google Developer Day 2010 Japan: プログラミング言語 Go (鵜飼 文敏)
Google Developer Day 2010 Japan: プログラミング言語 Go (鵜飼 文敏)
 
シェル芸初心者によるシェル芸入門
シェル芸初心者によるシェル芸入門シェル芸初心者によるシェル芸入門
シェル芸初心者によるシェル芸入門
 
Boost Tour 1.48.0 diff
Boost Tour 1.48.0 diffBoost Tour 1.48.0 diff
Boost Tour 1.48.0 diff
 
Python 機械学習プログラミング データ分析ライブラリー解説編
Python 機械学習プログラミング データ分析ライブラリー解説編Python 機械学習プログラミング データ分析ライブラリー解説編
Python 機械学習プログラミング データ分析ライブラリー解説編
 
「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12
「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12
「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12
 
Boost Tour 1_58_0 merge
Boost Tour 1_58_0 mergeBoost Tour 1_58_0 merge
Boost Tour 1_58_0 merge
 
Lisp tutorial for Pythonista : Day 1
Lisp tutorial for Pythonista : Day 1Lisp tutorial for Pythonista : Day 1
Lisp tutorial for Pythonista : Day 1
 
謎の言語Forthが謎なので実装した
謎の言語Forthが謎なので実装した謎の言語Forthが謎なので実装した
謎の言語Forthが謎なので実装した
 
One - Common Lispでもワンライナーしたい
One - Common LispでもワンライナーしたいOne - Common Lispでもワンライナーしたい
One - Common Lispでもワンライナーしたい
 
PHPの今とこれから2014
PHPの今とこれから2014PHPの今とこれから2014
PHPの今とこれから2014
 
PowerShellが苦手だった男がPowerShellを愛するようになるまで
PowerShellが苦手だった男がPowerShellを愛するようになるまでPowerShellが苦手だった男がPowerShellを愛するようになるまで
PowerShellが苦手だった男がPowerShellを愛するようになるまで
 

Andere mochten auch

The Spiritual Cure, An Explanation To Surah Al Fatihah,
The Spiritual Cure, An Explanation To Surah Al Fatihah,The Spiritual Cure, An Explanation To Surah Al Fatihah,
The Spiritual Cure, An Explanation To Surah Al Fatihah,
creatorsslave
 
Avance Werving en Selectie
Avance Werving en SelectieAvance Werving en Selectie
Avance Werving en Selectie
overgeldt
 
Topic 9: Build it and They Will Learn
Topic 9: Build it and They Will LearnTopic 9: Build it and They Will Learn
Topic 9: Build it and They Will Learn
bgalloway
 
Men and The Universe By Ibn Al-Qayyem
Men and The Universe By Ibn Al-QayyemMen and The Universe By Ibn Al-Qayyem
Men and The Universe By Ibn Al-Qayyem
creatorsslave
 
Cutting It
Cutting ItCutting It
Cutting It
HollyLC
 
Fav Music Mags Pp
Fav Music Mags PpFav Music Mags Pp
Fav Music Mags Pp
HollyLC
 
TV Drama Presentation
TV Drama PresentationTV Drama Presentation
TV Drama Presentation
HollyLC
 
Construction Presentation
Construction PresentationConstruction Presentation
Construction Presentation
HollyLC
 
Technological Convergence
Technological ConvergenceTechnological Convergence
Technological Convergence
HollyLC
 
Universal case study
Universal case studyUniversal case study
Universal case study
HollyLC
 

Andere mochten auch (20)

Zer Slide
Zer SlideZer Slide
Zer Slide
 
Brains! - Iveszics Alexander & Ömböli Krisztián
Brains! - Iveszics Alexander & Ömböli KrisztiánBrains! - Iveszics Alexander & Ömböli Krisztián
Brains! - Iveszics Alexander & Ömböli Krisztián
 
Shb calendar 2014 jul-dec
Shb calendar 2014 jul-decShb calendar 2014 jul-dec
Shb calendar 2014 jul-dec
 
HTML5で始める簡単アプリ制作
HTML5で始める簡単アプリ制作HTML5で始める簡単アプリ制作
HTML5で始める簡単アプリ制作
 
The Spiritual Cure, An Explanation To Surah Al Fatihah,
The Spiritual Cure, An Explanation To Surah Al Fatihah,The Spiritual Cure, An Explanation To Surah Al Fatihah,
The Spiritual Cure, An Explanation To Surah Al Fatihah,
 
Why I Wake Up At 4:22am
Why I Wake Up At 4:22amWhy I Wake Up At 4:22am
Why I Wake Up At 4:22am
 
What is Peek
What is PeekWhat is Peek
What is Peek
 
Avance Werving en Selectie
Avance Werving en SelectieAvance Werving en Selectie
Avance Werving en Selectie
 
Mphone
MphoneMphone
Mphone
 
Ud matematik
Ud matematikUd matematik
Ud matematik
 
L'escola
L'escolaL'escola
L'escola
 
D Me Powerpoint09
D Me Powerpoint09D Me Powerpoint09
D Me Powerpoint09
 
Topic 9: Build it and They Will Learn
Topic 9: Build it and They Will LearnTopic 9: Build it and They Will Learn
Topic 9: Build it and They Will Learn
 
Men and The Universe By Ibn Al-Qayyem
Men and The Universe By Ibn Al-QayyemMen and The Universe By Ibn Al-Qayyem
Men and The Universe By Ibn Al-Qayyem
 
Cutting It
Cutting ItCutting It
Cutting It
 
Fav Music Mags Pp
Fav Music Mags PpFav Music Mags Pp
Fav Music Mags Pp
 
TV Drama Presentation
TV Drama PresentationTV Drama Presentation
TV Drama Presentation
 
Construction Presentation
Construction PresentationConstruction Presentation
Construction Presentation
 
Technological Convergence
Technological ConvergenceTechnological Convergence
Technological Convergence
 
Universal case study
Universal case studyUniversal case study
Universal case study
 

Ähnlich wie ひのきのぼうだけで全クリ目指す

Python Kyoto study
Python Kyoto studyPython Kyoto study
Python Kyoto study
Naoya Inada
 
Javaセキュアコーディングセミナー東京第3回講義
Javaセキュアコーディングセミナー東京第3回講義Javaセキュアコーディングセミナー東京第3回講義
Javaセキュアコーディングセミナー東京第3回講義
JPCERT Coordination Center
 
おまえらこのライブラリ使ってないの? m9 (2013-07)
おまえらこのライブラリ使ってないの? m9	(2013-07)おまえらこのライブラリ使ってないの? m9	(2013-07)
おまえらこのライブラリ使ってないの? m9 (2013-07)
Toru Furukawa
 
Replace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JPReplace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JP
Akira Takahashi
 
Using PyFoam as library(第25回オープンCAE勉強会@関西)
Using PyFoam as library(第25回オープンCAE勉強会@関西)Using PyFoam as library(第25回オープンCAE勉強会@関西)
Using PyFoam as library(第25回オープンCAE勉強会@関西)
TatsuyaKatayama
 

Ähnlich wie ひのきのぼうだけで全クリ目指す (20)

20170131 python3 6 PEP526
20170131 python3 6 PEP526 20170131 python3 6 PEP526
20170131 python3 6 PEP526
 
研究生のためのC++ no.2
研究生のためのC++ no.2研究生のためのC++ no.2
研究生のためのC++ no.2
 
Python Kyoto study
Python Kyoto studyPython Kyoto study
Python Kyoto study
 
Subprocess no susume
Subprocess no susumeSubprocess no susume
Subprocess no susume
 
Javaセキュアコーディングセミナー東京第3回講義
Javaセキュアコーディングセミナー東京第3回講義Javaセキュアコーディングセミナー東京第3回講義
Javaセキュアコーディングセミナー東京第3回講義
 
おまえらこのライブラリ使ってないの? m9 (2013-07)
おまえらこのライブラリ使ってないの? m9	(2013-07)おまえらこのライブラリ使ってないの? m9	(2013-07)
おまえらこのライブラリ使ってないの? m9 (2013-07)
 
みんなのPython勉強会#77 パッケージングしよう
みんなのPython勉強会#77 パッケージングしようみんなのPython勉強会#77 パッケージングしよう
みんなのPython勉強会#77 パッケージングしよう
 
ALPSチュートリアル(4) Python入門
ALPSチュートリアル(4) Python入門ALPSチュートリアル(4) Python入門
ALPSチュートリアル(4) Python入門
 
debexpo(mentors.d.n)をハックするには
debexpo(mentors.d.n)をハックするにはdebexpo(mentors.d.n)をハックするには
debexpo(mentors.d.n)をハックするには
 
Replace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JPReplace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JP
 
Fab
FabFab
Fab
 
Using PyFoam as library(第25回オープンCAE勉強会@関西)
Using PyFoam as library(第25回オープンCAE勉強会@関西)Using PyFoam as library(第25回オープンCAE勉強会@関西)
Using PyFoam as library(第25回オープンCAE勉強会@関西)
 
Cython intro prelerease
Cython intro prelereaseCython intro prelerease
Cython intro prelerease
 
rpi_handson_2.5
rpi_handson_2.5rpi_handson_2.5
rpi_handson_2.5
 
ソフトウェア工学2023 14 ビルド
ソフトウェア工学2023 14 ビルドソフトウェア工学2023 14 ビルド
ソフトウェア工学2023 14 ビルド
 
behatエクステンションの作り方
behatエクステンションの作り方behatエクステンションの作り方
behatエクステンションの作り方
 
Pythonで始めるDropboxAPI
Pythonで始めるDropboxAPIPythonで始めるDropboxAPI
Pythonで始めるDropboxAPI
 
Ansible入門...?
Ansible入門...?Ansible入門...?
Ansible入門...?
 
NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門
 
「Python言語」はじめの一歩 / First step of Python
「Python言語」はじめの一歩 / First step of Python「Python言語」はじめの一歩 / First step of Python
「Python言語」はじめの一歩 / First step of Python
 

ひのきのぼうだけで全クリ目指す

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n