[英]Paramiko: Asynchronous reading for long shell script output using 'select'
我從這里得到以下代碼,並做了一些修改:
#!/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], [], [])
要么
r, w, x = select.select([channel], [], [], 10.0)
您可以通過在while true
后面放置一個簡單的print語句來查看CPU的差異。 在0.0秒的超時語句中,您將看到它連續命中。 在更大的超時情況下,您會看到它只命中了一次(而CPU則更低)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.