LoginSignup
1
1

More than 3 years have passed since last update.

Pythonで__END__(もどき)を実現する

Last updated at Posted at 2020-05-29

PerlやRubyの__END__。それなりに大きいテキストデータをプログラムの末尾に置いておけるので便利である。しかし、Pythonでは使用できない。複数行文字列はあるが、後置することができない。

そこで、こういうものを末尾に置くと「データ」が読み込めるモジュールを作ってみた。

'''
__END__
データ
'''

ただし、引用符は'''"""の両方に対応しているが、同じものをデータ部内に書くことができない。不完全ではあるが、改善が難しそうなので現時点でのものを公開する。

Python2/3両対応です(PyPyでも動くようです)。

enddata.py
import sys
from io import StringIO

def getdata():
    ret = StringIO()
    with open(sys._getframe().f_back.f_code.co_filename,'rb') as f:
        strStart = None
        while True:
            line = f.readline()
            if not line or line.rstrip().decode('utf-8') == '__END__':
                break
            strStart = line.rstrip()
        # read until the str finishes as ret should not contain trailing quote
        prev = None
        while True:
            line = f.readline()
            if not line or line.rstrip() == strStart.rstrip():
                break
            if prev is not None:
                ret.write(prev)
            prev = line.decode('utf-8')
        if prev is not None:
            ret.write(prev)
    ret.seek(0)
    return ret
test.py
#!/usr/bin/python
from enddata import getdata

print(getdata().read().rstrip())

'''
__END__
Hello END World!
'''

Hello END World!が出力される。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1