PythonNewbie
PythonNewbie

Reputation: 1163

Python - Starting a thread kills all threads using sys.exit()

Im having issue with threading. Basically when I do a threading.Thread(target=self.d3JpdGVDU1Y(payload)).start() which means it will create a new thread with a target and params for that function.

My problem is that when I do a sys.exit() on that thread, it stops the whole script even though it is supposed to continue to run the main(): function since we are just creating a new thread for the different functions.

def main():
    # Discord send
    if self.discordWebhook:
        threading.Thread(
            target=sendtoWebhook.c2VuZFRvRGlzY29yZA(self, self.discordWebhook, payload)).start()

    # Send to CSV write
    threading.Thread(target=self.d3JpdGVDU1Y(payload)).start()

--------------------------------

class sendtoWebhook:

    def c2VuZFRvRGlzY29yZA(self, webhook, payload):
        response = requests.post('{}/slack'.format(webhook), json=discord)

        if response.status_code == 200:
            print("Sent to discord!")
            sys.exit()

        elif response.status_code == 429:
            print("Failed printing")
            sys.exit()

What it supposed to do is to kill the thread for the sendtoWebhook function and not the all using sys.exit() or am I doing something wrong?

Upvotes: 1

Views: 327

Answers (2)

Japkeerat Singh
Japkeerat Singh

Reputation: 67

I think you are trying to close the execution of the thread. (Can't verify by commenting because of low reps).

sys.exit() is used to exit from Python, not from a thread. This means that if you call sys.exit() you will close the whole execution.

Just replace sys.exit() with thread.exit() and that should work fine for you. thread.exit() is used to close the execution of a thread.

Upvotes: 1

pilcrow
pilcrow

Reputation: 58651

Your code never starts a thread.

In main(), you do this:

Thread(target=func_that_calls_sys_exit(foo, bar), ...)

when you mean to do this:

Thread(target=func_that_calls_sys_exit, args=(foo, bar), ...)

The former invokes the method before any thread is created, intending to pass its return value to the Thread constructor's target parameter. That invocation of course raises a SystemExit, thus terminating your process before any threads can be created.

Upvotes: 3

Related Questions