Skip to content

Commit 6d4ba1c

Browse files
committed
Flush libc stdout/stderr in suppress_stdout_stderr
1 parent 99f2ebf commit 6d4ba1c

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

llama_cpp/_utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import sys
3+
import ctypes
34

45
from typing import Any, Dict
56

@@ -16,6 +17,14 @@ class suppress_stdout_stderr(object):
1617
# this context manager inside of a __del__ method
1718
sys = sys
1819
os = os
20+
libc = ctypes.CDLL(None)
21+
try:
22+
c_stdout = ctypes.c_void_p.in_dll(libc, "stdout")
23+
c_stderr = ctypes.c_void_p.in_dll(libc, "stderr")
24+
except:
25+
# macOS
26+
c_stdout = ctypes.c_void_p.in_dll(libc, "__stdoutp")
27+
c_stderr = ctypes.c_void_p.in_dll(libc, "__stderrp")
1928

2029
def __init__(self, disable: bool = True):
2130
self.disable = disable
@@ -25,6 +34,9 @@ def __enter__(self):
2534
if self.disable:
2635
return self
2736

37+
self.libc.fflush(self.c_stdout)
38+
self.libc.fflush(self.c_stderr)
39+
2840
self.old_stdout_fileno_undup = STDOUT_FILENO
2941
self.old_stderr_fileno_undup = STDERR_FILENO
3042

@@ -45,6 +57,9 @@ def __exit__(self, *_):
4557
if self.disable:
4658
return
4759

60+
self.libc.fflush(self.c_stdout)
61+
self.libc.fflush(self.c_stderr)
62+
4863
# Check if sys.stdout and sys.stderr have fileno method
4964
self.sys.stdout = self.old_stdout
5065
self.sys.stderr = self.old_stderr

0 commit comments

Comments
 (0)