Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Markdownのpythonコードブロックからdoctest実行用ファイルを作成する
"""
# 下記を実行するとコードブロックからdoctestファイル ham_doctest.py、egg_doctest.py を作成する
$ python3 create_doctestfile.py ham.md egg.md
# doctestは下記で実行可能
$ python3 ham_doctest.py
"""
import sys
def trim_comment(line):
"""行途中からのコメントを削除"""
if ' #' in line:
line = line.split(' #')[0] + '\n'
return line
def extract(filename):
"""必要な行だけを出力する"""
is_inside_block = False
with open(filename) as f:
for line in f:
if line.startswith('```python'):
is_inside_block = True
elif line.startswith('(注'):
is_inside_block = False
elif line.startswith('```'):
is_inside_block = False
yield '\n'
elif line.startswith('# '):
continue
elif is_inside_block:
yield trim_comment(line)
def main():
filenames = sys.argv[1:]
for filename in filenames:
with open(filename.replace('.md', '_doctest.py'), 'w') as f:
f.write("'''\n")
for line in extract(filename):
f.write(line)
f.write("""'''
if __name__ == '__main__':
import doctest
# ...をに値と一致させる
# 例外は型のみ判定する
flags = doctest.ELLIPSIS|doctest.IGNORE_EXCEPTION_DETAIL
doctest.testmod(optionflags=flags)
""")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment