開発環境
- 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 2(from/from*)を解いてみる。
その他参考書籍
2(from/from*)
コード(BBEdit)
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))
入出力結果(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.
>>> name = 'mymod.py'
>>> from mymod import test1, test2
>>> 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.
>>> name = 'mymod.py'
>>> from mymod import *
>>> test1(name)
{'lines': 38, 'chars': 767}
>>> test2(name)
{'lines': 38, 'chars': 767}
>>> quit()
$
0 コメント:
コメントを投稿