@@ -392,6 +392,12 @@ def __init__(
392392 self .default_to_shell = False # Attempt to run unrecognized commands as shell commands
393393 self .allow_redirection = allow_redirection # Security setting to prevent redirection of stdout
394394
395+ # If True, cmd2 treats redirected input (pipes/files) as an interactive session.
396+ # It will display the prompt before reading each line to synchronize with
397+ # automation tools (like Pexpect) and will skip echoing the input to prevent
398+ # duplicate prompts in the output.
399+ self .interactive_pipe = False
400+
395401 # Attributes which ARE dynamically settable via the set command at runtime
396402 self .always_show_hint = False
397403 self .debug = False
@@ -3218,18 +3224,25 @@ def _read_raw_input(
32183224 return session .prompt (prompt , completer = completer , ** prompt_kwargs )
32193225
32203226 # We're not at a terminal, so we're likely reading from a file or a pipe.
3221- # We wait for a line of data before we print anything.
3227+ prompt_obj = prompt () if callable (prompt ) else prompt
3228+ prompt_str = prompt_obj .value if isinstance (prompt_obj , ANSI ) else prompt_obj
3229+
3230+ # If this is an interactive pipe, then display the prompt first
3231+ if self .interactive_pipe :
3232+ self .poutput (prompt_str , end = '' )
3233+ self .stdout .flush ()
3234+
3235+ # Wait for the next line of input
32223236 line = self .stdin .readline ()
32233237
32243238 # If the stream is empty, we've reached the end of the input.
32253239 if not line :
32263240 raise EOFError
32273241
3228- # If echo is on, we want the output to look like a session transcript.
3229- # Print the prompt and the command before the results.
3230- if self .echo :
3231- prompt_obj = prompt () if callable (prompt ) else prompt
3232- prompt_str = prompt_obj .value if isinstance (prompt_obj , ANSI ) else prompt_obj
3242+ # If not interactive and echo is on, we want the output to simulate a
3243+ # live session. Print the prompt and the command so they appear in the
3244+ # output stream before the results.
3245+ if not self .interactive_pipe and self .echo :
32333246 end = "" if line .endswith ('\n ' ) else "\n "
32343247
32353248 self .poutput (f'{ prompt_str } { line } ' , end = end )
0 commit comments