Command Redirection – How to Redirect stdin and stdout to Output

pipestdinstdouttee

Suppose I have the Python script:

#!/usr/bin/env python
input('Y/n: ')
print('Next line')

After I press Y, I want both the terminal and my output.txt containing:

Y/n: Y
Next line

Running the following I don't get Y in the output:

$ python ask.py 2>&1 | tee output.txt

How can I include my response in the output?

Best Answer

Along the lines of what you already have (tested with python3):

tee -a output.txt | python ask.py 2>&1 | tee -a output.txt

As a downside, you will need to explicitly type something after the python script terminates, to make the first tee attempt writing to the pipe, receive a SIGPIPE and exit. You may be able to overcome this limitation with:

tee -a output.txt | { python ask.py 2>&1; kill 0; } | tee -a output.txt

Where kill is used to kill all the processes in the current process group (i.e. the dedicated process group the pipeline is run as). (But note that caveats may apply).

An alternative, if script is available to you, may be:

script -q -c 'python ask.py' output.txt

In this case python will be connected to a pseudo-terminal device, ensuring it behaves as if it were run interactively on a terminal.

Related Question