我正在使用paramiko在远程计算机上通过ssh执行长时间运行的python脚本。就像魅力一样,到目前为止没有问题。
不幸的是,仅在脚本完成后才显示stdout
(分别为stderr
)!但是,由于执行时间长,我更希望输出每个新行,因为它是打印的,而不是之后。
remote = paramiko.SSHClient()
remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote.connect("host", username="uname", password="pwd")
# myScript produces continuous output, that I want to capture as it appears
stdin, stdout, stderr = remote.exec_command("python myScript.py")
stdin.close()
for line in stdout.read().splitlines():
print(line)
如何实现? 注意:当然,可以将输出通过管道传递到一个文件,并通过另一个ssh session “减少”该文件,但这非常丑陋,我需要一个更干净的,理想的pythonic解决方案:) 最佳答案
如read([size]) documentation中所指定,如果您未指定size
,它将读取直到EOF为止,这会使脚本等待命令结束,然后从read()
返回并打印任何输出。
检查以下答案:How to loop until EOF in Python?和How to do a "While not EOF"有关如何用尽类文件对象的示例。