我收到错误:UnboundLocalError:在赋值之前引用的局部变量'porc'

时间:2017-01-25 08:53:12

标签: python python-2.7 raspberry-pi subprocess raspbian

我正在尝试执行此代码

command3.py

ui = shinyUI(
  fluidPage(
    tags$head(tags$style(HTML('.irs-from, .irs-to, .irs-min, .irs-max, .irs-single {
            visibility: hidden !important;
    }'))),
    sliderInput("test", "slider", 0,12, value = c(0,12))))
server = shinyServer(function(input, output){

})

runApp(list(ui=ui, server=server))

LED3.py

import microgear.client as microgear
import os
os.system("sudo pigpiod")
import pigpio
import RPi.GPIO as GPIO
import subprocess



piMASTER = pigpio.pi()


####################### NETPIE ####################    
appid = 'xxxxxxxxx'
gearkey = 'xxxxxxxxxx'
gearsecret =  'xxxxxxxxxxxxxxxxxxxx'

microgear.create(gearkey,gearsecret,appid,{'debugmode': True})




def connection():
    print "Now I am connected with netpie"




def subscription(topic,message):
        print topic+" "+message
        if message == "ON":
            proc = subprocess.Popen(["sudo", "python", "LED3.py"], shell = False)
        else:
            piMASTER.write(4, 0)
            proc.terminate()



def disconnect():
     print "disconnect is work"

microgear.setalias("switch")
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/mails")
microgear.connect(True)
消息传入时

如果消息为“ON”,LED3.py仍然有效 但如果消息为“OFF”,我收到此错误

import time
import pigpio
import RPi.GPIO as GPIO

pi= pigpio.pi()
while True:
    pi.write(4, 1)          #Set LED pin 7 to HIGH
    time.sleep(1)           #Delay 1 second
    pi.write(4, 0)      #Set LED pin 7 to LOW
    time.sleep(1)

*对不起,如果我的英语不好。我刚开始学习python。

2 个答案:

答案 0 :(得分:1)

显然如果message不是!="ON",那么在分配之前引用proc,就像错误明确指出:

if message == "ON":
    proc = subprocess.Popen(["sudo", "python", "LED3.py"], shell = False) # assigning proc
else:
    piMASTER.write(4, 0)
    proc.terminate() # referencing proc

答案 1 :(得分:0)

如果message不等于OFF,则Python将执行proc.terminate()proc未定义。

您需要在proc语句之前实例化if。 (另一个问题是 - 我不清楚subprocess究竟做了什么。)