2017-12-02 6 views
1

소켓 (ardSocket)에 쓰려고 시도하는 코드가 있는데, 예외를 throw하면 다시 연결하려고 시도합니다. 나는 소켓 변수를 전역 변수로 선언하여 별도의 함수에 할당 될 때 나머지 프로그램에서도 액세스 할 수 있어야하지만 어떤 이유로 여전히 예외가 발생합니다. 코드의 시작 부분에 실제 소켓을 전역으로 선언하면 모든 것이 잘 동작합니다. ardSocket = None을 전역으로 선언 한 다음 별도의 함수로 사용하도록 할당 할 수없는 이유는 무엇입니까?파이썬 2.7 전역 변수?

#!/usr/bin/env python 
''' 
Arduino LED values: 0=down, 1=up, 2=blink 
''' 
import os 
from subprocess import Popen, PIPE, STDOUT 
import serial 
import time 

ardSocket = None 

def ardConnect(): 
    arduinoFound=False 

    while arduinoFound==False: 
     try: 
      ardSocket=serial.Serial('/dev/ttyUSB0',9600) 
      arduinoFound=True 
      print "Arduino connected" 
     except: 
      print "Arduino not found. retrying in 10 seconds" 
      time.sleep(10) 

while 1==1: 
    response=Popen(['ping','-c 1','google.com'],stdout=PIPE,stderr=STDOUT) 
    stdout,nothing=response.communicate() 

    if "Name or service not known" in stdout:    #If DNS fails 
     try: 
      ardSocket.write('0')        #Solid RED LED 
     except: 
      ardConnect() 

    else: 
     pingTestArray=stdout.splitlines()     #Split ping output into array by lines 
     pingTestArrayList=pingTestArray[4].split(" ")  #Split the line containing packet loss by words 
     packetLoss=pingTestArrayList[5].replace('%','')  #Remove the % from the element containing packet loss number 
                  #and assign value to packetLoss var 


     if int(packetLoss) > 30 and int(packetLoss) < 95: #If packet loss > 30% && < 95% warn, FLASH RED LED 
      try: 
       ardSocket.write('2') 
      except: 
       print "ard error" 
       ardConnect() 
     elif int(packetLoss) > 94:       #Network is down, >95% packet loss, SOLID RED LED 
      try: 
       ardSocket.write('0') 
      except: 
       print "ard error" 
       ardConnect() 
     else: 
      try: 
       ardSocket.write('1')       #Else show good, GREEN LED 
      except: 
       print "ard error" 
       ardConnect() 
    time.sleep(5) 
+2

'ardConnect'가 로컬에 할당 중입니다. 같은 이름의 글로벌이 존재하는 것은 중요하지 않습니다. – user2357112

+1

함수에서'ardSocket'을 선언하는 것을 잊어 버렸기 때문에 할당 된 함수의 지역 변수입니다. – kindall

+0

내가해도 : 글로벌 ardSocket 여전히 오류가 발생합니다. –

답변

0

변수를 전역 함수로 선언하여이를 해결했습니다. 의견/도움에 감사드립니다.