Question

I'm trying to collect data which is being parsed via a socket. Here is my code:

import pickle
import SocketServer

class SocketReciever(SocketServer.BaseRequestHandler):

    def handle(self):
        sint = self.request.makefile('rb')
        objectt = pickle.load(sint)
        #print(objectt)
        ParentClassCall(objectt)

if __name__ == "__main__":
    HOST, PORT = "localhost", 60

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), SocketReciever)
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

data=[]
def ParentClassCall(currentdata):
    data.append(currentdata)

My question is how would I call the ParentClassCall function from within the SocketReciever class?

I know this method is plagued with security problems but it will be run on a computer without internet access.

Était-ce utile?

La solution

Python never gets to defining ParentClassCall() since it stops at the line server.serve_forever(). Define the function before the main stanza.

Autres conseils

Here's a simplified version of your example, to demonstrate the problem:

class Foo(object):

  def __init__(self):
    pass

  def do_something(self):
    not_yet_defined_function()

if __name__ == "__main__":
  foo = Foo()
  foo.do_something()

def not_yet_defined_function():
  print "It worked!"

The result is the same:

Traceback (most recent call last):
  File "tmp.py", line 11, in <module>
    foo.do_something()
  File "tmp.py", line 7, in do_something
    not_yet_defined_function()

The problem is that you are trying to access the function before it's defined. The python interpreter reads through the file sequentially, executing commands in order. The class and def keywords are just commands that create (class and function) objects. So, you need to make sure you define all your objects before you start using them.

By changing the example to define the function first:

class Foo(object):

  def __init__(self):
    pass

  def do_something(self):
    not_yet_defined_function()

def not_yet_defined_function():
  print "It worked!"

if __name__ == "__main__":
  foo = Foo()
  foo.do_something()

Then you get the result you want:

lap:~$ python tmp2.py
It worked!
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top