Python Paramiko:使用“选择”异步读取长shell脚本输出
我从中获得了以下代码,几乎没有修改:Python Paramiko:使用“选择”异步读取长shell脚本输出,python,python-2.7,ssh,paramiko,Python,Python 2.7,Ssh,Paramiko,我从中获得了以下代码,几乎没有修改: #!/usr/bin/env python import paramiko import select server = "19
#!/usr/bin/env python
import paramiko
import select
server = "192.168.100.100"
port = 22
name = "root"
password = "pass"
def main():
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
client.connect(server, port, name, password)
channel = client.get_transport().open_session()
channel.exec_command("/tmp/test.sh")
while True:
if channel.exit_status_ready():
break
r, w, x = select.select([channel], [], [], 0.0)
if len(r) > 0:
print channel.recv(1024)
if __name__ == "__main__":
main()
其中test.sh包含以下内容:
#!/usr/bin/env bash
while true
do
echo "Message"
sleep 1
done
因此,在执行python脚本之后,脚本的CPU使用率将上升到100%。这意味着此选择函数不会等到一个或多个文件描述符准备好进行某种I/O。据我们所知,这是一个繁忙的循环问题,其中“while…”。。。“循环”将连续迭代,即使未提供读取数据。如何使其异步读取远程输出 您的问题是在选择时超时设置为0秒,所以它根本不会阻塞。默认设置是根据需要进行阻塞,因此可以从select中取出timeout参数,或者将其更改为更大的值:
r, w, x = select.select([channel], [], [])
或
您可以在CPU上看到差异,也可以在while true之后添加一个简单的print语句。在0.0秒超时语句中,您将看到它连续命中。在更大的超时情况下,您将看到它正好命中一次,cpu将大大降低。当select执行此操作时,您希望发生什么?您的代码依赖于紧随其后的输出。例如,如果bash脚本中的睡眠时间等于5。Select.Select应等待直到生成输出,而不是在没有任何睡眠的情况下循环。也许我误解了“选择”的含义。我想做的是异步读取生成的输出。您使用的是“异步”一词,但根据您的解释,我认为这不是您想要的。听起来像是说要选择阻止,直到得到结果为止。您只是不想让它无休止地循环,而是在不耗尽CPU的情况下等待。是吗?@Eli是的,这是真的。谢谢你的解释。
r, w, x = select.select([channel], [], [], 10.0)