[Tutor] Namespace Problem
Carroll, Barry
Barry.Carroll at psc.com
Mon Nov 7 22:01:47 CET 2005
Bob:
Yes I did mean 'import' and yes there is more to the function. Here is the
entire program.
########################
import socket
import struct
# data packet flags
ABC = 1
DEF = 2
GHI = 4
JKL = 8
seq = 0
buf = 8192 # This is the max_packet_size defined in the SocketServer module
addr = ('localhost', 12345) # Host and port used by the server
def do_stuff(in_str):
hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str))
newstr = hdr+in_str
if(sock.sendto(newstr,addr)):
response = sock.recv(buf)
flags, retseq, dlen = struct.unpack('@2BH', response[:4])
print "flags: 0x%X, retseq: %u, dlen: %u" % (flags, retseq, dlen)
response = response[4:]
rsphdr=eval(response[:response.find(')')+1])
response = response[response.find(')')+2:]
resptupl = (rsphdr, response)
seq += 1
return resptupl
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg
# Send messages
while (1):
data = raw_input('>> ')
if not data:
break
else:
print "Sending message '",data,"'"
ret_data = do_stuff(data)
print "Got back: ", ret_data
sock.close( )
########################
Here is a trace of program execution.
>>>>>>>>>>>>>>>>>>>>>>>>
===Enter message to send to server===
>> send some data
Sending message ' send some data '
Traceback (most recent call last):
File "./bgctest.py", line 40, in ?
ret_data = do_stuff(data)
File "./bgctest.py", line 15, in do_stuff
hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str))
UnboundLocalError: local variable 'seq' referenced before
assignment>>>>>>>>>>>>>>>>>>>>>>>>
I can't figure it out.
Barry
> -----Original Message-----
> From: bob [mailto:bgailer at alum.rpi.edu]
> Sent: Friday, November 04, 2005 6:32 PM
> To: Carroll, Barry; 'tutor at python.org'
> Cc: Carroll, Barry
> Subject: Re: [Tutor] Namespace Problem
>
> At 05:47 PM 11/4/2005, Carroll, Barry wrote:
> >I have a function that makes use of several global variables:
> >
> >##########
> >Include struct
>
> Did you mean "import"?
>
> >ABC = 1
> >DEF = 2
> >xyz = 0
> >def do_stuff(in_str):
> > hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
> > newstr = hdr+in_str
>
> Works find for me. Is there anything else you are not showing us?
>
<<snip>>
More information about the Tutor
mailing list