Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input to stdin when tee is used

Tags:

bash

tee

I typically use tee to save program out to some other file, e.g.

python -c "print('haha');" | tee -a /tmp/tmp.txt

However, this can't work when the program need to read from stdin

python -c "print('haha');import pdb; pdb.set_trace()" | tee -a /tmp/tmp.txt

Program will hang there without printing anything. How to deal with this? Thanks...

like image 753
Nan Hua Avatar asked Jan 28 '26 15:01

Nan Hua


1 Answers

Try:

python -c "print('haha');import pdb, sys; pdb.Pdb(stdout=sys.stderr).set_trace()" | tee -a /tmp/tmp.txt

Or, if you are on Linux:

stdbuf -o0 python -c "print('haha');import pdb, sys; pdb.set_trace()" | tee -a /tmp/tmp.txt

In the first case above, the pdb is directed to send its output to stderr. This means that it does not go to tee and instead goes directly to the terminal.

In the second case, the stdbuf utility is used to turn off output buffering. stdbuf is part of GNU coreutils.

Improved version

While the above code runs, pdb behaves differently when its stdout is not a tty. In particular, it does not support all of pdb's interactive command-line features, such as control keys. As pointed out by blueyed, the script command is able to overcome this so that the program runs as if its stdout was not re-directed:

script -q -c 'python -c "import pdb, sys; pdb.set_trace()"' /dev/null | tee -a /tmp/tmp.txt
like image 147
John1024 Avatar answered Jan 31 '26 07:01

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!