简体   繁体   English

无法从python脚本输出中读取值

[英]Can't read value from python script output

I've got 2 raspberrypi devices. 我有2个raspberrypi设备。 First is measuring temperature, second one is displaying it. 首先是测量温度,第二个是显示温度。 I've wrote some python scripts to manage sending temperature results. 我写了一些python脚本来管理发送温度结果。

Server script: 服务器脚本:

import RPi.GPIO as GPIO
import dht11
import time
import datetime
import sys
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 17
instance = dht11.DHT11(pin=17)

result = instance.read()

out = str(result.temperature) + " " + str(result.humidity)

sys.stdout.write(out)
sys.stdout.flush()
sys.exit(0)

Client script 客户端脚本

#!/usr/bin/python
import math
import time
import os
import Adafruit_CharLCD as LCD
# Initialize the LCD using the pins 
lcd = LCD.Adafruit_CharLCDPlate()

lcd.set_color(1.0, 1.0, 1.0)
lcd.clear()
ws_dht11 = ""
while True:
        ws_dht11 = str(os.system('ssh pi@weatherstation.local \'python ~/Apps/DHT11_Python/dht11_ssh_read.py\''))
        if ws_dht11<>'0 0':
                break;
print 'F'
print ws_dht11

The problem is with ws_dht11 variable. 问题出在ws_dht11变量上。 It seems it doesn't receive any value, instead of this server script is printing results. 它似乎没有收到任何值,而不是这个服务器脚本是打印结果。 How can I repair it? 我该怎么修呢?

os.system returns the exit code of the process you ran, which is going to be 0 in this case (I assume ssh even passes the return code back, which is not necessarily the case). os.system返回您运行的进程的退出代码,在这种情况下将返回0(我假设ssh甚至将返回代码传回,但情况不一定如此)。 I think what you are looking for is os.popen() which executes a command and allows you to read its output to stdout. 我认为你正在寻找的是os.popen(),它执行一个命令并允许你将其输出读取到stdout。
This is a very superficial answer, I suspect this is a very weird way of achieving communication, but I'm just answering your specific question w/o thinking. 这是一个非常肤浅的答案,我怀疑这是一种非常奇怪的实现沟通的方式,但我只是回答你没有想到的具体问题。

You are simply running a process which then returns said process exit code. 您只是运行一个进程,然后返回所述进程退出代码。

A better solution would be to have a listening socket to communicate between the hosts, or use some sort of HTTP API, such as REST or XML, to fetch the value from host A and host B. 更好的解决方案是使用侦听套接字在主机之间进行通信,或使用某种HTTP API(如REST或XML)从主机A和主机B获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM