MCPcopy Create free account
hub / github.com/cloudpipe/cloudpickle / _file_reduce

Function _file_reduce

cloudpickle/cloudpickle.py:967–1008  ·  view source on GitHub ↗

Save a file.

(obj)

Source from the content-addressed store, hash-verified

965
966
967def _file_reduce(obj):
968 """Save a file."""
969 import io
970
971 if not hasattr(obj, "name") or not hasattr(obj, "mode"):
972 raise pickle.PicklingError(
973 "Cannot pickle files that do not map to an actual file"
974 )
975 if obj is sys.stdout:
976 return getattr, (sys, "stdout")
977 if obj is sys.stderr:
978 return getattr, (sys, "stderr")
979 if obj is sys.stdin:
980 raise pickle.PicklingError("Cannot pickle standard input")
981 if obj.closed:
982 raise pickle.PicklingError("Cannot pickle closed files")
983 if hasattr(obj, "isatty") and obj.isatty():
984 raise pickle.PicklingError("Cannot pickle files that map to tty objects")
985 if "r" not in obj.mode and "+" not in obj.mode:
986 raise pickle.PicklingError(
987 "Cannot pickle files that are not opened for reading: %s" % obj.mode
988 )
989
990 name = obj.name
991
992 retval = io.StringIO()
993
994 try:
995 # Read the whole file
996 curloc = obj.tell()
997 obj.seek(0)
998 contents = obj.read()
999 obj.seek(curloc)
1000 except OSError as e:
1001 raise pickle.PicklingError(
1002 "Cannot pickle file %s as it cannot be read" % name
1003 ) from e
1004 retval.write(contents)
1005 retval.seek(curloc)
1006
1007 retval.name = name
1008 return _file_reconstructor, (retval,)
1009
1010
1011def _getset_descriptor_reduce(obj):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected