实时读取服务器端输出

问题描述:

我正在尝试在我的服务器上处理来自我的相机的图像,并在我的本地机器上实时处理后获取信息.我可以在我的服务器上获得必要的信息作为终端输出,但在我的服务器程序运行之前,我无法将此信息放入本地机器上的 python 代码中.我试过这个代码:

I'm trying to process images from my camera on my server and get the information after processing on my local machine in real-time. I can get necessary information as terminal outputs on my server, but I can't put this info in my python code on local machine, until my server program is running. I'm tried this code:

cmd="sshpass -p 'pass' ssh -Y user@ip -t 'process_image; bash -l'"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print(line)
    p.stdout.close()
    p.wait()

但它不起作用 - 看起来这段代码只是暂停了我的程序.我试图将输出写入文件而不是从本地机器读取文件,但它扭曲了我的数据.如何实时读取服务器的终端输出?

But it doesn't work - it looks like this code just paused my program. I tried to write output to file and than read file from local machine, but it distorts my data. What can i do to read terminal output from server in real-time?

由于您使用 bufsize=1 后输出将被行缓冲,那么您可以这样做:

Since the output is going to be line buffered since you use bufsize=1, then you could just do:

cmd="sshpass -p 'pass' ssh -Y user@ip -t 'process_image; bash -l'"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in p.stdout:
    print(line)
    .....

当然,这假设您的命令为您提供了您期望的输出.

Of course, this assumes your command is giving you the output you expect.