開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART V.(Modules and Packages)、Test Your Knowledge: Part V Exercises 5(Package imports.)を解いてみる。
その他参考書籍
5(Package imports.)
コード(BBEdit)
mypkg/mymod.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sys
def countLines1(name):
with open(name) as f:
count = len(f.readlines())
return count
def countChars1(name):
with open(name) as f:
count = len(f.read())
return count
def test1(name):
return {'lines':countLines1(name), 'chars':countChars1(name)}
def countLines2(file):
return len(file.readlines())
def countChars2(file):
return len(file.read())
def test2(name):
with open(name) as f:
lines = countLines2(f)
f.seek(0)
chars = len(f.read())
return {'lines':lines, 'chars':chars}
if __name__ == '__main__':
try:
name = sys.argv[1]
except:
name = 'mymod.py'
print(test1(name))
print(test2(name))
mypkg/__init__.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
print("Hello, 'mypkg/__init__.py' world!")
入出力結果(Terminal)
$ python3
Python 3.3.5 (default, Mar 15 2014, 14:51:54)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import mypkg.mymod
Hello, 'mypkg/__init__.py' world!
>>> name = './mypkg/mymod.py'
>>> mypkg.mymod.test1(name)
{'lines': 38, 'chars': 767}
>>> mypkg.mymod.test2(name)
{'lines': 38, 'chars': 767}
>>> from mypkg.mymod import *
>>> test1(name)
{'lines': 38, 'chars': 767}
>>> test2(name)
{'lines': 38, 'chars': 767}
>>> quit()
$ python3
Python 3.3.5 (default, Mar 15 2014, 14:51:54)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from mypkg.mymod import *
Hello, 'mypkg/__init__.py' world!
>>> name = './mypkg/mymod.py'
>>> test1(name)
{'lines': 38, 'chars': 767}
>>> test2(name)
{'lines': 38, 'chars': 767}
>>> quit()
$
0 コメント:
コメントを投稿