gpt4 book ai didi

Python 2.7 全局变量?

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:30 25 4
gpt4 key购买 nike

我有一些代码尝试写入套接字(ardSocket),如果它抛出异常,它将尝试重新连接。我将套接字变量声明为全局变量,以便在单独的函数中分配时,程序的其余部分仍然可以访问它,但由于某种原因仍然会引发异常。当我在代码开头全局声明实际的套接字时,一切正常。为什么我不能全局声明 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)

最佳答案

通过在函数内声明全局变量解决了这个问题。感谢评论/帮助。

关于Python 2.7 全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47605078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com