Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Flush libc stdout/stderr in suppress_stdout_stderr #2015

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions llama_cpp/_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import sys
import ctypes

from typing import Any, Dict

Expand All @@ -16,6 +17,14 @@ class suppress_stdout_stderr(object):
# this context manager inside of a __del__ method
sys = sys
os = os
libc = ctypes.CDLL(None)
try:
c_stdout = ctypes.c_void_p.in_dll(libc, "stdout")
c_stderr = ctypes.c_void_p.in_dll(libc, "stderr")
except:
# macOS
c_stdout = ctypes.c_void_p.in_dll(libc, "__stdoutp")
c_stderr = ctypes.c_void_p.in_dll(libc, "__stderrp")

def __init__(self, disable: bool = True):
self.disable = disable
Expand All @@ -25,6 +34,9 @@ def __enter__(self):
if self.disable:
return self

self.libc.fflush(self.c_stdout)
self.libc.fflush(self.c_stderr)

self.old_stdout_fileno_undup = STDOUT_FILENO
self.old_stderr_fileno_undup = STDERR_FILENO

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

self.libc.fflush(self.c_stdout)
self.libc.fflush(self.c_stderr)

# Check if sys.stdout and sys.stderr have fileno method
self.sys.stdout = self.old_stdout
self.sys.stderr = self.old_stderr
Expand Down