file_object.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from .info import check_PY2
  2. check_PY2()
  3. import ctypes
  4. from ctypes import (byref, pythonapi,
  5. c_int, c_char_p, c_void_p, py_object, c_ssize_t)
  6. class FileObject(ctypes.Structure):
  7. _fields_ = [
  8. #("_ob_next", c_void_p),
  9. #("_ob_prev", c_void_p),
  10. ("ob_refcnt", c_ssize_t),
  11. ("ob_type", c_void_p),
  12. ("fp", c_void_p),
  13. ("name", py_object),
  14. ("mode", py_object),
  15. ("close", c_void_p),
  16. ("softspace", c_int),
  17. ("binary", c_int),
  18. ("buf", c_char_p),
  19. ("bufend", c_char_p),
  20. ("bufptr", c_char_p),
  21. ("setbuf", c_char_p),
  22. ("univ_newline", c_int),
  23. ("newlinetypes", c_int),
  24. ("skipnextlf", c_int),
  25. ("encoding", py_object),
  26. ("errors", py_object),
  27. ("weakreflist", py_object),
  28. ("unlocked_count", c_int),
  29. ("readable", c_int),
  30. ("writable", c_int),
  31. ]
  32. @classmethod
  33. def from_file(cls, f):
  34. if not isinstance(f, file):
  35. raise TypeError("f has to be a file")
  36. return cls.from_address(id(f))
  37. def set_encoding(self, encoding):
  38. if not isinstance(encoding, str):
  39. raise TypeError("encoding has to be a str")
  40. pythonapi.PyFile_SetEncoding(byref(self), encoding)
  41. def copy_file_pointer(self, f):
  42. if not isinstance(f, file):
  43. raise TypeError("f has to be a file")
  44. self.fp = pythonapi.PyFile_AsFile(py_object(f))