gpt4 book ai didi

python - readline 在读取 "watch"命令输出时卡在 paramiko.Channel 上

转载 作者:行者123 更新时间:2023-12-04 16:16:29 24 4
gpt4 key购买 nike

我正在测试此代码以读取 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())

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

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

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

(在 Python 3.4.2 和 paramiko 1.15.1 上测试)

编辑 1:我合并了 channel.set_combine_stderr(True) as suggested in this answer to a related question ,但仍然没有成功。但是,watch 确实会产生大量输出,所以问题可能就在于此。事实上,使用这个命令删除了挂起:

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

所以,这个问题可能几乎是 Paramiko ssh die/hang with big output 的重复, 但让我想知道是否 真的没有办法使用 .readline() (在这种情况下通过 __next__ 调用) 并且必须诉诸以固定的缓冲区大小读取并手动组装行。

最佳答案

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

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

忙着循环

stdout.readline(some_fixed_size)

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

关于python - readline 在读取 "watch"命令输出时卡在 paramiko.Channel 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61466282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com