Skip to content

Commit 659686a

Browse files
authored
fix: enable Python UTF-8 mode to fix open() encoding default (#66)
The guest has no locale configured, so CPython defaults all I/O to ASCII. This causes UnicodeEncodeError when writing non-ASCII characters via open(path, 'w'). Setting Py_UTF8Mode = 1 before Py_Initialize() enables UTF-8 mode globally, making stdout/stderr/open() all default to UTF-8 without needing per-stream reconfigure calls. Signed-off-by: danbugs <danilochiarlone@gmail.com>
1 parent 5198570 commit 659686a

1 file changed

Lines changed: 2 additions & 7 deletions

File tree

examples/python-agent-driver/hl_pydriver.c

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -234,17 +234,12 @@ static void py_run_user_code(const uint8_t *fc, size_t fc_len)
234234

235235
static void py_initialize_once(void)
236236
{
237+
Py_UTF8Mode = 1;
237238
Py_Initialize();
238239

239-
/* sys.argv so scripts that look at it don't crash. Also force
240-
* stdout/stderr to UTF-8 — the guest has no locale configured,
241-
* so Python defaults to ASCII and any non-ASCII char (em-dash,
242-
* smart quotes, …) in a script's print() raises UnicodeEncodeError. */
243240
PyRun_SimpleString(
244241
"import sys\n"
245-
"sys.argv = ['hl_pydriver']\n"
246-
"sys.stdout.reconfigure(encoding='utf-8')\n"
247-
"sys.stderr.reconfigure(encoding='utf-8')\n");
242+
"sys.argv = ['hl_pydriver']\n");
248243

249244
/* Pre-import the python-agent stack so every subsequent call
250245
* through the v2 callback sees a warm sys.modules and pays only

0 commit comments

Comments
 (0)