Achieve __END__ in Python

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

Achieve __END__ in Python
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Start / end match in python regular expression
Daily AtCoder # 36 in Python
Clustering text in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
File operations in Python
Read DXF in python
Daily AtCoder # 53 in Python
Key input in Python
Use config.ini in Python
Solve ABC168D in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python
Simple gRPC in Python
Daily AtCoder # 24 in Python