0

I'm trying to set up a UDP server with Twisted folliowing this http://twistedmatrix.com/documents/current/core/howto/udp.html

However, I've hit a brickwall just starting. I tried this sample code:

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

class Echo(DatagramProtocol):

    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)
        self.transport.write(data, (host, port))

reactor.listenUDP(9999, Echo())
reactor.run()

And I get this:

def datagramReceived(self, data, (host, port)):
                                 ^
SyntaxError: invalid syntax

I'm new to Python so I'm clueless. I stripped the code down to the minimum, commenting everything but the class declaration and the method header (adding a pass) but I get the same. Are those paired parameters not supported anymore?

cangrejo
  • 2,189
  • 3
  • 24
  • 31
  • 1
    What Python version are you using? Also, are you sure there isn't an indentation error? – BrenBarn Oct 13 '12 at 18:23
  • 2.7, and there are 4 spaces on every indent. – cangrejo Oct 13 '12 at 18:26
  • That syntax was removed in Python 3, but still works in Python 2.7. Are you absolutely sure that: a) the code is being run with Python 2.7 (i.e., do you also have a Python 3 installed that might be running instead); b) the code you pasted is exactly the code you are running? – BrenBarn Oct 13 '12 at 18:33
  • That's right. Python 3 is the one doing the job, so it won't allow the double parameter. – cangrejo Oct 13 '12 at 18:38

1 Answers1

3

Are you sure it's python 2.7. Because PEP 3113 -- Removal of Tuple Parameter Unpacking describes the removal of that syntax in Python 3. As a test when I run the below dummy function in python 2.7 it works. In Python 3.2 it gives me your exact same error:

def datagramReceived(self, data, (host, port)):
    pass

python 3 error:

    def datagramReceived(self, data, (host, port)):
                                     ^
SyntaxError: invalid syntax

try this in your code just to be sure of your python version:

import sys
print(sys.version)
Marwan Alsabbagh
  • 25,364
  • 9
  • 55
  • 65
  • I think this was it. I had told PyDev to use 2.7 grammar so I assumed it would interpret it as 2.7 code. Looks like I was wrong. – cangrejo Oct 13 '12 at 18:36
  • I have a question on this one, anyone know how to adapt this code for python3? Im on an upgrade from python2 to 3 for my programs – user1829877 Dec 20 '20 at 18:53