首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 2.7全局变量?

Python 2.7全局变量?
EN

Stack Overflow用户
提问于 2017-12-02 13:54:29
回答 0查看 935关注 0票数 1

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

代码语言:javascript
复制
#!/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)
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47605078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档