@@ -329,8 +329,10 @@ async def process_control(self, msg):
329329 except Exception :
330330 self .log .error ("Exception in control handler:" , exc_info = True ) # noqa: G201
331331
332- sys .stdout .flush ()
333- sys .stderr .flush ()
332+ if sys .stdout is not None :
333+ sys .stdout .flush ()
334+ if sys .stderr is not None :
335+ sys .stderr .flush ()
334336 self ._publish_status_and_flush ("idle" , "control" , self .control_stream )
335337
336338 def should_handle (self , stream , msg , idents ):
@@ -404,8 +406,10 @@ async def dispatch_shell(self, msg):
404406 except Exception :
405407 self .log .debug ("Unable to signal in post_handler_hook:" , exc_info = True )
406408
407- sys .stdout .flush ()
408- sys .stderr .flush ()
409+ if sys .stdout is not None :
410+ sys .stdout .flush ()
411+ if sys .stderr is not None :
412+ sys .stderr .flush ()
409413 self ._publish_status_and_flush ("idle" , "shell" , self .shell_stream )
410414
411415 def pre_handler_hook (self ):
@@ -748,8 +752,10 @@ async def execute_request(self, stream, ident, parent):
748752 reply_content = await reply_content
749753
750754 # Flush output before sending the reply.
751- sys .stdout .flush ()
752- sys .stderr .flush ()
755+ if sys .stdout is not None :
756+ sys .stdout .flush ()
757+ if sys .stderr is not None :
758+ sys .stderr .flush ()
753759 # FIXME: on rare occasions, the flush doesn't seem to make it to the
754760 # clients... This seems to mitigate the problem, but we definitely need
755761 # to better understand what's going on.
@@ -1083,8 +1089,10 @@ async def apply_request(self, stream, ident, parent): # pragma: no cover
10831089 reply_content , result_buf = self .do_apply (content , bufs , msg_id , md )
10841090
10851091 # flush i/o
1086- sys .stdout .flush ()
1087- sys .stderr .flush ()
1092+ if sys .stdout is not None :
1093+ sys .stdout .flush ()
1094+ if sys .stderr is not None :
1095+ sys .stderr .flush ()
10881096
10891097 md = self .finish_metadata (parent , md , reply_content )
10901098 if not self .session :
@@ -1258,8 +1266,10 @@ def raw_input(self, prompt=""):
12581266
12591267 def _input_request (self , prompt , ident , parent , password = False ):
12601268 # Flush output before making the request.
1261- sys .stderr .flush ()
1262- sys .stdout .flush ()
1269+ if sys .stdout is not None :
1270+ sys .stdout .flush ()
1271+ if sys .stderr is not None :
1272+ sys .stderr .flush ()
12631273
12641274 # flush the stdin socket, to purge stale replies
12651275 while True :
0 commit comments