開発環境
- macOS Catalina - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 10(Reading and Writing Files)、Exercise 5の解答を求めてみる。
コード
#!/usr/bin/env python3
from unittest import TestCase, main
from test.support import captured_stdout
from typing import TextIO
from io import StringIO
print('5.')
class MyTestCase(TestCase):
def test1(self):
in_file = StringIO('''Example
# Comment
# Comment
Data line
''')
with captured_stdout() as stdout:
process_file(in_file)
self.assertEqual(stdout.getvalue(), 'Data line\n\n')
def test2(self):
in_file = StringIO('''Example
# Comment
# Comment
''')
with captured_stdout() as stdout:
process_file(in_file)
self.assertEqual(stdout.getvalue(), '\n')
def skip_header(reader: TextIO) -> str:
_ = reader.readline()
line = reader.readline()
while line.startswith('#'):
line = reader.readline()
return line
def process_file(reader: TextIO) -> None:
line = skip_header(reader).strip()
if line == '':
print()
else:
print(line)
print(reader.read())
if __name__ == "__main__":
main()
入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))
% ./sample5.py -v
5.
test1 (__main__.MyTestCase) ... ok
test2 (__main__.MyTestCase) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
%
0 コメント:
コメントを投稿