5

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?

1
  • 1
    @Quasímodo Well my real script is a lot more complicated, uses the logging module, input() and print(). I'm trying to modify that currently, if there just isn't a simple Linux solution. But a simple Linux solution is much preferred over modifying my Python script. What if say the Python script is a system script that I can't modify. – simonzack Mar 15 at 11:22
7

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.