readline 在读取 "watch" 命令输出时挂在 paramiko.Channel

readline hangs on paramiko.Channel when reading "watch" command output

我正在测试此代码以读取 watch 命令的输出。我怀疑它与 watch 的工作方式有关,但我不知道出了什么问题或如何解决它:

import paramiko

host = "micro"
# timeout = 2  # Succeeds
timeout = 3  # Hangs!
command = 'ls / && watch -n2 \'touch "f$(date).txt"\''

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(host, password='', look_for_keys=False)

transport = ssh_client.get_transport()
channel = transport.open_session()
channel.get_pty()
channel.settimeout(timeout)
channel.set_combine_stderr(True)
stdout = channel.makefile()
channel.exec_command(command)

for line in stdout:  # Hangs here
    print(line.strip())

有几个类似的问题,其中一些很旧(1, 2,可能还有其他问题)

其他不使用 watch 的命令也不会发生这种情况。

有人知道这个特定命令有什么特别之处和/或如何可靠地为读取操作设置超时吗?

(在 Python 3.4.2 和 paramiko 1.15.1 上测试)

编辑 1:我合并了 channel.set_combine_stderr(True) ,但仍然没有成功。但是,watch 确实产生了很多输出,所以问题可能就在于此。实际上,使用此命令删除了挂起:

command = 'ls / && watch -n2 \'touch "f$(date).txt"\' > /dev/null'

所以,这个问题可能几乎是 的重复,但让我想知道 是否真的没有办法使用 .readline()(通过 __next__在这种情况下) 并且必须求助于使用固定缓冲区大小和 assemble 手动读取行。

这可能挂起,因为 watch 不产生换行符。如果一个替换

for line in stdout:
    print(line.strip())

忙着循环

stdout.readline(some_fixed_size)

可以看出字节中从来没有包含换行符。因此,这是一个非常特殊的案例,与其他问题和 SO 问题中报告的其他挂起无关。