Message184312
| Author |
vstinner |
| Recipients |
alex, barry, belopolsky, brett.cannon, ncoghlan, rhettinger, vstinner |
| Date |
2013年03月16日.13:38:52 |
| SpamBayes Score |
-1.0 |
| Marked as misclassified |
Yes |
| Message-id |
<1363441132.62.0.332991996968.issue15805@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
If such context manager is added, it should be documented that it does not work with subprocess or C functions writing directly into the file descriptor 1.
For such issues, I'm using dup2(). Example from my pysandbox project:
@contextlib.contextmanager
def capture_stdout():
import sys
import tempfile
stdout_fd = sys.stdout.fileno()
with tempfile.TemporaryFile(mode='w+b') as tmp:
stdout_copy = os.dup(stdout_fd)
try:
sys.stdout.flush()
os.dup2(tmp.fileno(), stdout_fd)
yield tmp
finally:
sys.stdout.flush()
os.dup2(stdout_copy, stdout_fd)
os.close(stdout_copy) |
|