33import bisect
44import os
55import re
6+ import sys
67from functools import cmp_to_key
78
89
@@ -154,8 +155,12 @@ def key_func(x):
154155
155156 def display_sorted (self ):
156157 """Displays the current sorted data."""
157- os .system ("cls" if os .name == "nt" else "clear" )
158- print ("--- Interactive Sorted Data ---" )
158+ output_stream = sys .stderr if self .args .stderr else sys .stdout
159+
160+ if not self .args .stderr :
161+ os .system ("cls" if os .name == "nt" else "clear" )
162+
163+ print ("--- Interactive Sorted Data ---" , file = output_stream )
159164 items_to_display = self .data
160165 if self .args .unique :
161166 items_to_display = sorted (
@@ -165,21 +170,39 @@ def display_sorted(self):
165170 items_to_display = reversed (items_to_display )
166171
167172 for item in items_to_display :
168- print (item )
169- print ("-----------------------------" )
173+ print (item , file = output_stream )
174+ print ("-----------------------------" , file = output_stream )
175+
176+ def output_final_sorted (self ):
177+ """Outputs the final sorted data to stdout (used when stderr flag is set)."""
178+ items_to_display = self .data
179+ if self .args .unique :
180+ items_to_display = sorted (
181+ set (items_to_display ), key = lambda x : self .data .index (x )
182+ ) # Maintain original order of first occurrence
183+ if self .args .reverse :
184+ items_to_display = reversed (items_to_display )
185+
186+ for item in items_to_display :
187+ print (item , file = sys .stdout )
170188
171189 def run (self ):
172190 """Runs the interactive sort application."""
173- print ("Enter lines of text. Press Ctrl+D (or Ctrl+Z then Enter on Windows) to finish." )
191+ output_stream = sys .stderr if self .args .stderr else sys .stdout
192+ print ("Enter lines of text. Press Ctrl+D (or Ctrl+Z then Enter on Windows) to finish." , file = output_stream )
174193 try :
175194 while True :
176195 line = input ()
177196 self .add_item (line )
178197 self .display_sorted ()
179198 except EOFError :
180- print ("\n End of input." )
199+ if self .args .stderr :
200+ # When using stderr flag, output final sorted result to stdout
201+ self .output_final_sorted ()
202+ else :
203+ print ("\n End of input." , file = output_stream )
181204 except KeyboardInterrupt :
182- print ("\n Exiting." )
205+ print ("\n Exiting." , file = output_stream )
183206
184207
185208def main ():
0 commit comments