@@ -771,20 +771,33 @@ def assignment( # noqa: C901, PLR0913
771771 # Redirect the output from pdna to a tmp file and then delete the file
772772 if self .tmp_dir is not None :
773773 output_file = Path (self .tmp_dir ) / 'pandana_stdout.txt'
774+
774775 original_stdout_fd = sys .stdout .fileno ()
775- with Path .open (output_file , 'w' ) as file :
776- os .dup2 (file .fileno (), original_stdout_fd )
777- net = pdna .Network (
778- nodes_df ['x' ],
779- nodes_df ['y' ],
780- open_edges_df ['start_nid' ],
781- open_edges_df ['end_nid' ],
782- open_edges_df [['fft' ]],
783- twoway = two_way_edges ,
784- )
785- # The file is automatically closed when exiting the with block
786- # `sys.stdout` is automatically restored to its original state because
787- # we duplicated the original descriptor to `stdout`.
776+
777+ # Save the original stdout to a new file descriptor
778+ saved_stdout_fd = os .dup (original_stdout_fd )
779+
780+ try :
781+ with Path .open (output_file , 'w' ) as file :
782+ os .dup2 (file .fileno (), original_stdout_fd )
783+ net = pdna .Network (
784+ nodes_df ['x' ],
785+ nodes_df ['y' ],
786+ open_edges_df ['start_nid' ],
787+ open_edges_df ['end_nid' ],
788+ open_edges_df [['fft' ]],
789+ twoway = two_way_edges ,
790+ )
791+ # The file is automatically closed when exiting the with block
792+ # `sys.stdout` is automatically restored to its original state because
793+ # we duplicated the original descriptor to `stdout`.
794+
795+ finally :
796+ # Restore the original stdout
797+ os .dup2 (saved_stdout_fd , original_stdout_fd )
798+ # Close the saved descriptor
799+ os .close (saved_stdout_fd )
800+
788801 if getattr (self , 'save_pandana' , True ):
789802 Path .unlink (output_file )
790803 else :
0 commit comments