1
私はソケット(ardSocket)に書き込もうとするコードをいくつか持っていますが、例外をスローすると再接続しようとします。私はソケット変数をグローバルとして宣言しました。別個の関数に代入されたときに、プログラムの残りの部分からアクセスできるはずですが、なんらかの理由でまだ例外がスローされます。実際のソケットをコードの先頭にグローバルに宣言すると、すべて正常に動作します。 ardSocket = Noneをグローバルに宣言できないのですが、それを別の関数で使用するために割り当てることができません。Python 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)
'ardConnect'がローカルに割り当てられています。同じ名前のグローバルが存在することは重要ではありません。 – user2357112
関数内で 'ardSocket'グローバルを宣言するのを忘れてしまいました。したがって、関数内でローカルに指定されています。 – kindall
私がしても:グローバルardSocket それでもエラーです。 –