22import os
33import os .path as op
44import tempfile
5- import base64
65from subprocess import Popen , check_output , PIPE , STDOUT , CalledProcessError
76from cloudpickle .compat import pickle
87from contextlib import contextmanager
@@ -38,15 +37,16 @@ def _make_cwd_env():
3837 return cloudpickle_repo_folder , env
3938
4039
41- def subprocess_pickle_echo (input_data , protocol = None , timeout = TIMEOUT ):
42- """Echo function with a child Python process
40+ def subprocess_pickle_string (input_data , protocol = None , timeout = TIMEOUT ,
41+ add_env = None ):
42+ """Retrieve pickle string of an object generated by a child Python process
4343
4444 Pickle the input data into a buffer, send it to a subprocess via
4545 stdin, expect the subprocess to unpickle, re-pickle that data back
4646 and send it back to the parent process via stdout for final unpickling.
4747
48- >>> subprocess_pickle_echo ([1, 'a', None])
49- [1, 'a', None]
48+ >>> testutils.subprocess_pickle_string ([1, 'a', None], protocol=2 )
49+ b' \x80 \x02 ]q \x00 (K \x01 X \x01 \x00 \x00 \x00 aq \x01 Ne.'
5050
5151 """
5252 # run then pickle_echo(protocol=protocol) in __main__:
@@ -56,6 +56,8 @@ def subprocess_pickle_echo(input_data, protocol=None, timeout=TIMEOUT):
5656 # which is deprecated in python 3.8
5757 cmd = [sys .executable , '-W ignore' , __file__ , "--protocol" , str (protocol )]
5858 cwd , env = _make_cwd_env ()
59+ if add_env :
60+ env .update (add_env )
5961 proc = Popen (cmd , stdin = PIPE , stdout = PIPE , stderr = PIPE , cwd = cwd , env = env ,
6062 bufsize = 4096 )
6163 pickle_string = dumps (input_data , protocol = protocol )
@@ -67,14 +69,30 @@ def subprocess_pickle_echo(input_data, protocol=None, timeout=TIMEOUT):
6769 message = "Subprocess returned %d: " % proc .returncode
6870 message += err .decode ('utf-8' )
6971 raise RuntimeError (message )
70- return loads ( out )
72+ return out
7173 except TimeoutExpired as e :
7274 proc .kill ()
7375 out , err = proc .communicate ()
7476 message = u"\n " .join ([out .decode ('utf-8' ), err .decode ('utf-8' )])
7577 raise RuntimeError (message ) from e
7678
7779
80+ def subprocess_pickle_echo (input_data , protocol = None , timeout = TIMEOUT ,
81+ add_env = None ):
82+ """Echo function with a child Python process
83+ Pickle the input data into a buffer, send it to a subprocess via
84+ stdin, expect the subprocess to unpickle, re-pickle that data back
85+ and send it back to the parent process via stdout for final unpickling.
86+ >>> subprocess_pickle_echo([1, 'a', None])
87+ [1, 'a', None]
88+ """
89+ out = subprocess_pickle_string (input_data ,
90+ protocol = protocol ,
91+ timeout = timeout ,
92+ add_env = add_env )
93+ return loads (out )
94+
95+
7896def _read_all_bytes (stream_in , chunk_size = 4096 ):
7997 all_data = b""
8098 while True :
0 commit comments