Perl and Ruby __END__
. It is convenient because you can put a reasonably large text data at the end of the program. But it's not available in Python. There is a multi-line string, but it cannot be followed.
So, I made a module that can read "data" by putting such a thing at the end.
'''
__END__
data
'''
However, although the quotation marks correspond to both '''
and " ""
, the same thing cannot be written in the data part. It is incomplete, but it seems difficult to improve, so at the moment Publish things.
It supports both Python 2/3 (it seems to work with 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!
Is output.
Recommended Posts