当我在类ser
之外分配它时,如何使用类方法中的ser
?就像跟随它在Window中不起作用一样。
import socket,
datetime,
threading,
os,
serial
# declare once
ser = serial.Serial('COM3', 19200)
class AServer(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
self.port = port
def now(self):
d = datetime.datetime.now()
return d.strftime("%d/%m/%y %H:%M:%S")
def run(self):
host = ''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, self.port))
print 'successfully, waiting...'
s.listen(1)
conn, addr = s.accept()
print 'contact', addr, 'on', self.now()
while 1:
try:
data = conn.recv(1024)
except socket.error:
print 'lost', addr, 'waiting..'
s.listen(1)
conn, addr = s.accept()
print 'contact', addr, 'on', self.now()
continue
if not data:
print 'lost', addr, 'waiting..'
s.listen(1)
conn, addr = s.accept()
print 'contact', addr, 'on', self.now()
else:
print "received msg:", data
conn.send('roger')
if data.startswith('blablabla'):
ser.write('\x02\x01\x80\x00\x03\x80')
else:
print "not ok"
t = AServer(80)
t.start()
最佳答案
这与Python的名称空间有关。您需要说要访问全局ser
变量
# declare once
ser = serial.Serial('COM3', 19200)
class AServer(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
self.port = port
global se
self._ser = ser # local reference to global variable
关于python - 如何从类方法中全局使用定义为ser的序列号?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11510941/