@@ -114,29 +114,33 @@ def launch(executable: Any,
114114
115115 # Do we write the Popen stdout to sys.stdout or to a file?
116116 subprocess_stdout = sys .stdout
117+ close_stdout = False # is true if we need to later close the file
117118 try :
118119 log_filename = kwargs ['logfile' ]
119120 except KeyError :
120121 log .info ('No logfile specified, using stdout for task output' )
121122 else :
122123 subprocess_stdout = open (log_filename , 'w' )
124+ close_stdout = True # Welp, gotta close it now
123125 log .info (f'Task output log file: { log_filename } ' )
124126
125127 # Repeat the same for stderr
126- task_stderr = subprocess .STDOUT
128+ subprocess_errfile = subprocess .STDOUT
129+ close_stderr = False
127130 try :
128- subprocess_stderr = kwargs ['errfile' ]
131+ subprocess_errfile = kwargs ['errfile' ]
129132 except KeyError :
130133 log .info ('No errfile specified, using STDOUT for task errors' )
131134 else :
132135 try :
133- task_stderr = open (subprocess_stderr , 'w' )
136+ subprocess_errfile = open (subprocess_errfile , 'w' )
134137 except OSError :
135- log .info (f'Could not open errfile { subprocess_stderr } , '
138+ log .info (f'Could not open errfile { subprocess_errfile } , '
136139 f'using STDOUT for task errors' )
137- task_stderr = subprocess .STDOUT
140+ subprocess_errfile = subprocess .STDOUT
138141 else :
139- log .info (f'Task error log file: { subprocess_stderr } ' )
142+ close_stderr = True
143+ log .info (f'Task error log file: { subprocess_errfile } ' )
140144
141145 task_env = kwargs .get ('task_env' , {})
142146 new_env = os .environ .copy ()
@@ -192,8 +196,9 @@ def launch(executable: Any,
192196
193197 cmd_lst = cmd .split ()
194198 try :
195- process = subprocess .Popen (cmd_lst , stdout = subprocess_stdout ,
196- stderr = task_stderr ,
199+ process = subprocess .Popen (cmd_lst ,
200+ stdout = subprocess_stdout ,
201+ stderr = subprocess_errfile ,
197202 cwd = working_dir ,
198203 preexec_fn = os .setsid , env = new_env ) # noqa: PLW1509 (TODO: look into this to potentially avoid deadlocks)
199204 except Exception as e :
@@ -213,6 +218,17 @@ def launch(executable: Any,
213218 finally :
214219 os .chdir (original_directory )
215220
221+ # Flush stdout and stderr because it's sometimes necessary on HPC
222+ # systems to ensure that the output is actually processed.
223+ subprocess_errfile .flush ()
224+ subprocess_stdout .flush ()
225+
226+ if close_stdout :
227+ subprocess_stdout .close ()
228+
229+ if close_stderr :
230+ subprocess_errfile .close ()
231+
216232 try :
217233 ret_val = process .wait (timeout )
218234 finish_time = time .time ()
@@ -304,6 +320,8 @@ def launch(executable: Any,
304320
305321 log .info (f'Task { task_name } finished with return value: { ret_val } ' )
306322
323+
324+
307325 os .chdir (original_directory )
308326 return task_name , ret_val
309327
0 commit comments