我需要在函数外部打印“ gas”的值。
已经尝试不使用global,并且给出了类似print (gas)
的打印语句。什么都不适合我。
def action(pin):
global gas
gas = 1
print('Sensor detected action!')
return
action(1)
print gas
结果是:
print gas
NameError: global name 'gas' is not defined
(已编辑)完整代码为
import sys
import Adafruit_DHT
import time
import httplib, json
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Connecting gas sensor with pin 16 of Raspbery Pi 3
gas = None #Initializing gas value as 0
def action(pin):
gas = 1
print('Sensor detected action!')
return gas
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
# print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity)
time.sleep(1)
temp = '{0:0.1f}'.format(temperature)
hum = '{0:0.1f}'.format(humidity)
GPIO.add_event_detect(16, GPIO.RISING)
GPIO.add_event_callback(16, action)
#print '{0:0.1f}'.format(temperature)
#print '{0:0.1f}'.format(humidity)
if temp == 0 or hum == 0:
#print "ERR_RANGE"
headers = { "charset" : "utf-8", "Content-Type": "application/json" }
conn = httplib.HTTPConnection("heatexchangelive.000webhostapp.com")
sample_1 = { "nodata" : no_data }
sampleJson_1 = json.dumps(sample_1, ensure_ascii = 'False')
conn.request("POST", "/rpi1/rpi.php", sampleJson_1, headers)
response = conn.getresponse()
print(response.read())
conn.close()
exit(0)
else:
#Sending the data to the server
headers = { "charset" : "utf-8", "Content-Type": "application/json" }
conn = httplib.HTTPConnection("heatexchangelive.000webhostapp.com")
print (gas)
sample = { "humidity" : hum, "temperature" : temp, "gas" : gas }
sampleJson = json.dumps(sample, ensure_ascii = 'False')
我得到的结果是,
pi@raspberrypi:~ $ sudo python tempNew.py
None
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
New record created successfully
alive
Sensor detected action!
Sensor detected action!
Sensor detected action!
Sensor detected action!
我的数据库始终在“ gas”中更新为0
这是数据库的屏幕截图,
答案 0 :(得分:0)
您可以return gas
,然后将打印语句更改为print action(1)
或者您必须在函数之外定义gas变量,然后才能使用全局语句。
答案 1 :(得分:0)
只需声明gas变量,顶部应显示None。
gas = None;
def action(pin):
global gas
gas = 1
print('Sensor detected action!')
return
action(1)
print(gas)