Skip to content

Commit

Permalink
stub out stdout_redirector [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
tlambert03 committed Mar 5, 2019
1 parent 2b37e90 commit 95184da
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion pycudadecon/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import tifffile as tf
import numpy as np
import warnings
from contextlib import contextmanager


PLAT = sys.platform
Expand All @@ -30,7 +31,9 @@ def array_is_otf(arr):
return False
if arr.shape[0] > arr.shape[1]:
return False
if not arr[:, 1].any():

# the first pixel of an OTF will always be 1.0 and the second column 0s
if arr[0, 0] == 1 and (not arr[:, 1].any()):
return True


Expand Down Expand Up @@ -123,3 +126,34 @@ def load_lib(libname):
raise Exception('didn\'t find it')
except Exception:
continue


# https://stackoverflow.com/questions/5081657/how-do-i-prevent-a-c-shared-library-to-print-on-stdout-in-python/17954769#17954769
@contextmanager
def stdout_redirected(to=os.devnull):
'''
import os
with stdout_redirected(to=filename):
print("from Python")
os.system("echo non-Python applications are also supported")
'''
fd = sys.stdout.fileno()

# assert that Python and C stdio write using the same file descriptor
# assert libc.fileno(ctypes.c_void_p.in_dll(libc, "stdout")) == fd == 1

def _redirect_stdout(to):
sys.stdout.close() # + implicit flush()
os.dup2(to.fileno(), fd) # fd writes to 'to' file
sys.stdout = os.fdopen(fd, 'w') # Python writes to fd

with os.fdopen(os.dup(fd), 'w') as old_stdout:
with open(to, 'w') as file:
_redirect_stdout(to=file)
try:
yield # allow code to be run with the redirected stdout
finally:
_redirect_stdout(to=old_stdout) # restore stdout.
# buffering and flags such as
# CLOEXEC may be different

0 comments on commit 95184da

Please sign in to comment.