首页 > 解决方案 > 获取和使用由 subprocess.check_output 远程运行的脚本的输出

问题描述

我很难找出如何用标题来表达我的问题,而且它可能不是有史以来最好的描述。但下面我将详细解释我的情况。如果有任何建议,我很乐意编辑标题。

我现在有两个 Raspberry Pi。以后还会有更多。Pi A 是运行代码并收集温度值的主机。Pi B 只是在那里运行传感器并收集温度和湿度值。

我试图在 Pi A 中拥有每个脚本,并使用 ssh 在其他机器上远程运行它们。

我正在尝试一个新事物,所以我将放两个我现在正在处理的简单代码。

第一个脚本是 af.py。它存储在 Pi A 中,但它将在 Pi B 中运行。

#!/usr/bin/env python

import Adafruit_DHT as dht
h, t = dht.read_retry(dht.DHT22, 4)

print('{0:0.1f} {1:0.1f}'.format(t, h))

输出是:

pi@raspberrypi:~/Temp_Codes $ python af.py
26.1 22.7
pi@raspberrypi:~/Temp_Codes $ 

第二个是 afvar.py。在这个脚本中,我让 Pi B 运行 af.py 但问题是,我希望能够直接获取 Pi B 传感器的值或输出,以便我可以继续在 afvar.py 中使用它们

#!/usr/bin/env python

import subprocess

#Here I am trying to get the temperature and humidity value inside these two variables t2 and h2

t2, h2 = subprocess.check_output("sshpass -p 'x' ssh pi@192.168.x.x python < /home/pi/tempLog/af.py", shell = True)

#Some other stuff using t2 and h2 .....
#like print "temp is %f and hum is %f" % (t2, h2)

目前它给了我这样的错误:

Traceback (most recent call last):
  File "afvar.py", line 16, in <module>
    t2, h2 = subprocess.check_output("sshpass -p 'x' ssh pi@192.168.x.x python < /home/pi/tempLog/af.py", shell = True)
ValueError: too many values to unpack

我正在尝试做的事情可能吗?我一直在检查互联网并尝试了不同的解决方案,但这是我目前陷入困境的地方。

标签: pythonsshraspberry-pisubprocess

解决方案


subprocess.check_output返回bytes。你想在那里分割的,可能是你的输出'{0:0.1f} {1:0.1f}'.format(t, h)

bytes因此,您首先必须将to解码str(并可能将其从尾随换行符中剥离)然后拆分它。

output = subprocess.check_output("sshpass -p 'x' ssh pi@192.168.x.x python < /home/pi/tempLog/af.py", shell = True)
output = output.decode().strip()
t2, h2 = output.split()

而且由于您可能希望温度和湿度为浮点数,最后解析它们:

t2, h2 = float(t2), float(h2)

推荐阅读