Python2.7全局变量?

2024-09-28 01:32:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码试图写入套接字(ardSocket),如果它抛出异常,它将尝试重新连接。我将socket变量声明为global,这样当在单独的函数中赋值时,程序的其余部分仍然可以访问它,但是由于某些原因仍然抛出了一个异常。当我在代码开头全局声明实际的套接字时,一切正常。为什么我不能全局声明ardSocket=None,然后分配它在一个单独的函数中使用?在

#!/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)

Tags: import声明ledtimepacketstdoutarduinowrite

热门问题