256 Kilobytes

Answers in Scripting and Automation | By August R. Garcia

Published 2 months agoSun, 15 Sep 2019 17:06:46 -0700 | Last update 2 months agoSun, 15 Sep 2019 20:49:11 -0700

799 views, 0 RAMs, and 0 comments

Tags: Python, Debugging

Profile Photo - August R. Garcia August R. Garcia LARPing as a Sysadmi... Portland, OR
🗎 207 🗨 1033 🐏 317
Site Owner

Normally, to kill a Python script while it is running, pressing CTRL+C will work. However, if there are multiple threads running because the program is multithreaded, this will not immediately kill everything. In some cases, this can leave you waiting indefinitely, depending on what is occuring in the other threads. There are "clean" ways to handle these threads, such as:

try:
    rows = some_function() 

    # Make some threads
    threads = list() 
    for row in rows:
        x = threading.Thread(target=some_other_function, args=([row]))
        threads.append(x)
        x.start()

except KeyboardInterrupt as e:
    # Wait for the threads to finish/join
    for index, thread in enumerate(threads):
            thread.join()
finally:
        print("The program has now exited...") 

However, when debugging, often what you may want to do is to just kill everything immediately with no concern for "properly" cleaning up other threads. Probably the easiest way to do this is:

  1. Press CTRL+Z. This will put the current Python script into the background, returning your cursor to the terminal. Note that the script will still be running in the background
  2. Run pkill -9 python from the terminal to kill all running Python processes. Make sure to do this or you can run into issues with the other script running in the background (e.g., if the script writes to a database)

To verify that the process has been killed, the command ps can be run to list running processes.

Download more RAM. 🐏 ⨉ 0 Posted by August R. Garcia 2 months ago

Edit History

• [2019-09-15 17:06 PDT] August R. Garcia (2 months ago)
🕓 Posted at 15 September, 2019 17:06 PM PDT

Sir, I can do you a nice SEO.

Post a New Comment

To leave a comment, login to your account or create an account.

Do you like having a good time?

Read Quality Articles

Read some quality articles. If you can manage to not get banned for like five minutes, you can even post your own articles.

View Articles →

Argue with People on the Internet

Use your account to explain why people are wrong on the Internet forum.

View Forum →

Vandalize the Wiki

Or don't. I'm not your dad.

View Wiki →

Ask and/or Answer Questions

If someone asks a terrible question, post a LMGTFY link.

View Answers →

Make Some Money

Hire freelancers and/or advertise your goods and/or services. Hire people directly. We're not a middleman or your dad. Manage your own business transactions.

Register an Account
You can also login to an existing account or recover your password. All use of this site is subject to terms outlined in the terms of service and privacy policy.