通过 ssh 实时查看脚本输出

通过 ssh 实时查看脚本输出

我正在尝试使用 ssh 在远程计算机上运行本地脚本。

假设这是printdelay.py我正在尝试运行的 python 脚本 ( ):

from time import sleep  
print("The first line")  
sleep(10)  
print("The second line")

我这样执行脚本:

cat printdelay.py | ssh user@host python

该脚本执行,但我注意到只有在整个脚本运行完成后我才能看到命令的输出。我希望看到脚本执行时的输出,即打印两行之间有延迟。

我注意到

cat printdelay.py | ssh -t -t user@host python

有点像我正在寻找的,但后来我在伪终端中看到很多噪音,而不是简单的线条打印。我想有更好的方法来做到这一点。

答案1

使用-upython 标志:

cat printdelay.py | ssh user@host python -u

您所看到的行为是因为,当 stdout 不是交互式设备(例如 tty 或 pty)时写入 stdout 时,该printf函数系列刷新缓冲区的频率较低。正如您发现的那样,除了给 Python 一个 pty 之外,您对此无能为力。这将起作用:

scp printdelay.py user@host:/tmp/timedelay.py
ssh -t user@host python /tmp/timedelay.py

(如果你只是这样做cat timedelay.py | ssh -tt user@host python,python 将有一个 pty 并且它会更频繁地刷新缓冲区,但是你还会遇到其他问题,例如,由于 pty 分配与 ssh 一起工作的方式,你的脚本将被打印到 stdout 。)

你也可以尝试使用 coreutils 命令 stdbuf

相关内容