Last active
November 15, 2019 00:18
-
-
Save ahartikainen/06192df9719031cf1a22b887b7b5d67b to your computer and use it in GitHub Desktop.
Silence C++ stdout (stderr still works)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import threading | |
import pystan | |
import logging | |
# silence logger, there are better ways to do this | |
# see PyStan docs | |
logging.getLogger("pystan").propagate=False | |
def drain_pipe(captured_stdout, stdout_pipe): | |
while True: | |
data = os.read(stdout_pipe[0], 1024) | |
if not data: | |
break | |
captured_stdout += data | |
def capture_output(function, *args, **kwargs): | |
""" | |
https://stackoverflow.com/questions/24277488/in-python-how-to-capture-the-stdout-from-a-c-shared-library-to-a-variable | |
""" | |
stdout_fileno = sys.stdout.fileno() | |
stdout_save = os.dup(stdout_fileno) | |
stdout_pipe = os.pipe() | |
os.dup2(stdout_pipe[1], stdout_fileno) | |
os.close(stdout_pipe[1]) | |
captured_stdout = b'' | |
t = threading.Thread(target=lambda:drain_pipe(captured_stdout, stdout_pipe)) | |
t.start() | |
# run user function | |
result = function(*args, **kwargs) | |
os.close(stdout_fileno) | |
t.join() | |
os.close(stdout_pipe[0]) | |
os.dup2(stdout_save, stdout_fileno) | |
os.close(stdout_save) | |
return result, captured_stdout.decode("utf-8") | |
stan_code = """ | |
parameters { | |
real y; | |
} | |
model { | |
y ~ normal(0,1); | |
} | |
""" | |
stan_model, _ = capture_output(pystan.StanModel, model_code=stan_code) | |
fit, _ = capture_output(stan_model.sampling) | |
print(fit) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment