FileStream.py 868 B

123456789101112131415161718192021222324252627
  1. #
  2. # Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3. # Use of this file is governed by the BSD 3-clause license that
  4. # can be found in the LICENSE.txt file in the project root.
  5. #
  6. #
  7. # This is an InputStream that is loaded from a file all at once
  8. # when you construct the object.
  9. #
  10. import codecs
  11. from antlr4.InputStream import InputStream
  12. class FileStream(InputStream):
  13. __slots__ = 'fileName'
  14. def __init__(self, fileName:str, encoding:str='ascii', errors:str='strict'):
  15. super().__init__(self.readDataFrom(fileName, encoding, errors))
  16. self.fileName = fileName
  17. def readDataFrom(self, fileName:str, encoding:str, errors:str='strict'):
  18. # read binary to avoid line ending conversion
  19. with open(fileName, 'rb') as file:
  20. bytes = file.read()
  21. return codecs.decode(bytes, encoding, errors)