sim*_*ack 5 pipe tee stdout stdin
假设我有 Python 脚本:
#!/usr/bin/env python
input('Y/n: ')
print('Next line')
Run Code Online (Sandbox Code Playgroud)
按 后Y
,我想要终端和我的output.txt
包含:
Y/n: Y
Next line
Run Code Online (Sandbox Code Playgroud)
运行以下我没有得到Y
输出:
$ python ask.py 2>&1 | tee output.txt
Run Code Online (Sandbox Code Playgroud)
如何在输出中包含我的响应?
沿着您已经拥有的内容(使用 测试python3
):
tee -a output.txt | python ask.py 2>&1 | tee -a output.txt
Run Code Online (Sandbox Code Playgroud)
不利的一面是,您需要在 python 脚本终止后显式键入一些内容,以便第一次tee
尝试写入管道、接收 aSIGPIPE
并退出。您可以通过以下方式克服此限制:
tee -a output.txt | { python ask.py 2>&1; kill 0; } | tee -a output.txt
Run Code Online (Sandbox Code Playgroud)
wherekill
用于杀死当前进程组中的所有进程(即运行管道的专用进程组)。(但请注意,可能存在警告)。
如果script
您可以使用另一种方法,则可能是:
script -q -c 'python ask.py' output.txt
Run Code Online (Sandbox Code Playgroud)
在这种情况下,python
将连接到伪终端设备,确保它的行为就像在终端上交互运行一样。