python/cpython · error

Could not convert pre-site command to Unicode\n

Error message

Could not convert pre-site command to Unicode\n

What it means

Emitted in run_presite (Python/pylifecycle.c) when PyUnicode_FromWideChar(config->run_presite, -1) returns NULL while converting the pre-site hook specification (set via -X presite=... / PYTHON_PRESITE, used by free-threading and debugging workflows to run a hook before site.py) from wchar_t to a Unicode object. The most common cause is MemoryError during interpreter bring-up; the pending exception is then printed via _PyErr_Print.

Source

Thrown at Python/pylifecycle.c:1293

    Py_DECREF(obj);
    Py_DECREF(attr);
    return NULL;
}


static void
run_presite(PyThreadState *tstate)
{
    PyInterpreterState *interp = tstate->interp;
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);

    if (!config->run_presite) {
        return;
    }

    PyObject *presite = PyUnicode_FromWideChar(config->run_presite, -1);
    if (presite == NULL) {
        fprintf(stderr, "Could not convert pre-site command to Unicode\n");
        _PyErr_Print(tstate);
        return;
    }

    // Accept "mod_name" and "mod_name:func_name" entry point syntax
    Py_ssize_t len = PyUnicode_GET_LENGTH(presite);
    Py_ssize_t pos = PyUnicode_FindChar(presite, ':', 0, len, 1);
    PyObject *mod_name = NULL;
    PyObject *func_name = NULL;
    PyObject *module = NULL;
    if (pos > 0) {
        mod_name = PyUnicode_Substring(presite, 0, pos);
        if (mod_name == NULL) {
            goto error;
        }

        func_name = PyUnicode_Substring(presite, pos + 1, len);
        if (func_name == NULL) {

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Verify the presite value is a short, valid ASCII module[/:func] string
  2. Rule out memory pressure at startup (raise limits, check ulimits/containers)
  3. Temporarily unset -X presite/PYTHONPRESITE to confirm the rest of startup is healthy

Example fix

# before
PYTHON_PRESITE=$'ÿþ(bad)' python app.py
# after
PYTHON_PRESITE=myhook:setup python app.py
Defensive patterns

Strategy: validation

Validate before calling

# bash: keep the hook spec short, ASCII, mod[:func]
case "$PYTHON_PRESITE" in
  *[!a-zA-Z0-9_.:]*) echo 'presite spec must be ASCII mod[:func]' >&2; exit 1;;
esac
PYTHON_PRESITE="$PYTHON_PRESITE" python app.py

Prevention

When it happens

Trigger: Configuring config->run_presite / -X presite=modname:funcname and hitting allocation failure or a conversion error in PyUnicode_FromWideChar at a point where the exception machinery is barely usable.

Common situations: Extremely memory-constrained startup; malformed wide-character strings set by embedding code; free-threaded debug builds using PYTHON_PRESITE for sanitizer hooks.

Related errors


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/cac8d2728dc77a9c. Report an issue: GitHub.