開発環境
- 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 1(Import basics)を解いてみる。
その他参考書籍
1(Import basics)
コード(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. >>> import mymod >>> name = 'mymod.py' >>> mymod.test1(name) {'lines': 38, 'chars': 767} >>> mymod.test2(name) {'lines': 38, 'chars': 767} >>> quit() $ ./mymod.py {'chars': 767, 'lines': 38} {'chars': 767, 'lines': 38} $ ./mymod.py sample.py {'lines': 25, 'chars': 444} {'lines': 25, 'chars': 444} $ wc -cl mymod.py 38 767 mymod.py $ wc -cl sample.py 25 444 sample.py $
0 コメント:
コメントを投稿