What are possible causes of my python script ending prematurely?

Question:

I have a python script that communicates with other software through TCP/IP protocol. It receives data in XML format from the software. This worked fine. However, since it is part of a larger project I packed the modules and installed them into my project environment.

In some mysterious way, my script in the project environment is ending prematurely.

The script ends somewhere in the function below because when I print the lines from the message it ends somewhere halfway.

    def to_line(self, message: RecievedMessage):
        sys.setrecursionlimit(10**6)
        if len(self.data[0]) > 0:
            size = ord(self.data[0])
            line = "".join(self.data[4:size + 4]).strip()
            # print(line)
            message.recieved_lines.append(RecievedMessage.RecievedLine(size=size, data=line))
            del self.data[0: size + 4]
            self.to_line(message)
        else:
            return message

I tried to find the obvious errors by breaking the code, such as setting the recursion limit to low. But the common errors are caught.

EDIT: to_line() method uses an if statement to check the recursive base case, instead of the previous try except block.

SOLUTION:

”’

def to_line(self) -> None:
    while len(self.data[0]) > 0:
        size = ord(self.data[0])
        line = "".join(self.data[4:size + 4]).strip()
        self.message.recieved_lines.append(RecievedMessage.RecievedLine(size=size, data=line))
        del self.data[0: size + 4]

”’

Asked By: Dorus

||

Answers:

You most likely ran out of memory. In this case, the python interpreter might just exit without an error message or with just the usual message from your operating system. (something like "[…] terminated unexpectedly")

It is generally a bad idea to increase the recursion limit. If you need a higher recursion limit, there is generally just a problem with your code. As a rule of thumb: If you can write something as a loop in Python, you should write it as a loop. Else you will keep all unneeded local variables in memory and quickly run out of it.

In your case, it is simple: Just replace if with while and remove the recursive call.

def to_line(self, message: RecievedMessage) -> RecievedMessage:
    while len(self.data[0]) > 0:
        size = ord(self.data[0])
        line = "".join(self.data[4:size + 4]).strip()
        # print(line)
        message.recieved_lines.append(RecievedMessage.RecievedLine(size=size, data=line))
        del self.data[0: size + 4]
    return message

There a further things that are strange in your code: What is self.data containing? If you call ord, it seemingly is a string (or a list of characters), but then len(self.data[0]) makes no sense.

Answered By: Dodezv