pykit3 is is a collection of toolkit in python3.

Documentation for the Code

k3thread is utility to create and operate thread.

Start a daemon thread after 0.2 seconds:

>>> th = daemon(lambda :1, after=0.2)

Stop a thread by sending a exception:

import time

def busy():
    while True:

t = daemon(busy)
send_exception(t, SystemExit)


exception k3thread.InvalidThreadIdError

Raised if a invalid thread id is used.

exception k3thread.SendRaiseError

Super class of exceptions raied when calling send_raise().


k3thread.start(target, name=None, args=None, kwargs=None, daemon=False, after=None)

Create and start a thread with the given args.

  • target (callable) – The callable object to run.

  • name – The thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

  • args – The argument tuple for the target invocation. Defaults to ().

  • kwargs (dict) – A dictionary of keyword arguments for the target invocation. Defaults to {}.

  • daemon (bool) –

    Whether to create a daemon thread.

    A daemon thread will quit when the main thread in a process quits. A non-daemon thread keeps running after main thread quits. A process does not quit if there are any non-daemon threads running.

  • after (bool) –

    If after is not None, it sleeps for after seconds before calling target.

    By default it is None.


the thread started.

Return type


k3thread.daemon(target, name=None, args=None, kwargs=None, after=None)

Create and start a daemon thread. It is same as start() except that it sets argument daemon=True.

k3thread.send_exception(thread, exctype)

Asynchronously raises an exception in the context of the given thread, which should cause the thread to exit silently (unless caught).

Caveat: this function does not work with pypy, because it relies on

pythonapi that pypy does not support.

Caveat: It might not work as expected:

The exception will be raised only when executing python bytecode. If your thread calls a native/built-in blocking function (such as time.sleep() and threading.Thread.join()), the exception will be raised only when execution returns to the python code.

There is also an issue if the built-in function internally calls PyErr_Clear(), which would effectively cancel your pending exception. You can try to raise it again.

Thus This function does not guarantee that a running thread will be interrupted and shut down when it is called.

  • thread (threading.Thread) – the thread in which to raise the exception.

  • exctype – A exception class that will be raised in the thread.

  • InvalidThreadIdError – if the given thread is not alive or found.

  • TypeError – if any input is illegal.

  • ValueError – if any input is illegal.

  • SendRaiseError – for other unexpected errors.

Indices and tables