python - 获取和使用由 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
我正在尝试做的事情可能吗?我一直在检查互联网并尝试了不同的解决方案,但这是我目前陷入困境的地方。
解决方案
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)
推荐阅读
- r - 我的闪亮代码的功能(单独的面板过滤器并为 radioButtons 选项插入 popify)
- lightbox2 - lightbox2 在实时预览中工作,但不在服务器上
- android - 为什么 ssh 包在发布版本中不起作用?
- java - 部署到 WebLogic 时出现“weblogic.application.ModuleException: java.lang.NoSuchMethodError:org.springframework.util.MultiValueMap.addAll”
- go - 如何在 Golang 中检索经过身份验证的用户
- javascript - 电子模态javascript按钮不起作用
- android - 选择单列值作为 livedata
- joomla3.0 - 在文章类别模块中显示完整的 Joomla 文章
- vba - 宏在应用于分段符时会导致 Word 崩溃
- javascript - 按下任何数学运算符时,Javascript计算器显示0