跳转到主要内容

线程安全的stdio代理

项目描述

stdio_proxy

PyPI PyPI Supported Python Versions GitHub license GitHub Actions (Tests)

stdio_proxy是一个线程安全的库,用于Python 2.7和Python 3.5+,可以将stdio临时重定向到另一个对象。

背景

Python 3.5+中的contextlib模块有redirect_stdoutredirect_stderr,分别是将sys.stdoutsys.stderr临时重定向到其他文件对象的有用函数。但是,这些函数对sys.stdoutsys.stderr有全局副作用。这意味着我们不能在大多数线程应用程序中使用这些函数。

  • Python代码
import contextlib
import io
import time
from concurrent.futures import ThreadPoolExecutor

def run(value):
    for i in range(2):
        print("Hello from {}:{}".format(value, i))
        time.sleep(1)

def run_hook(value):
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        run(value)
    return buf.getvalue()

with ThreadPoolExecutor() as executor:
    f1 = executor.submit(run, "th1")
    f2 = executor.submit(run_hook, "th2")
    f1.result()
    result = f2.result()
    print("===Done===")
    print("Redirected Stdout:\n{}".format(result))
  • 我们想要的功能
Hello from th1:0
Hello from th1:1
===Done===
Redirected Stdout:
Hello from th2:0
Hello from th2:1
  • 实际输出的示例
Hello from th1:0
===Done===
Redirected Stdout:
Hello from th2:0
Hello from th1:1
Hello from th2:1

这个库旨在在线程应用程序中正确重定向这些stdio。只需用以下代码替换run_hook函数,结果将与“我们想要的功能”完全相同 :)。

def run_hook(value):
    buf = io.BytesIO()
    with stdio_proxy.redirect_stdout(buf):
        run(value)
    return buf.getvalue()

安装

$ pip install stdio-proxy

用法

  • 将缓冲区重定向到stdin
buf = io.BytesIO(b"foo\n")
with stdio_proxy.redirect_stdin(buf):
    print("Read: {}".format(sys.stdin.readline()))
  • stdout重定向到缓冲区
buf = io.BytesIO()
with stdio_proxy.redirect_stdout(buf):
    print("foo")
print("Redirected: {}".format(buf.getvalue()))
  • stderr重定向到缓冲区
buf = io.BytesIO()
with stdio_proxy.redirect_stderr(buf):
    sys.stderr.write("foo\n")
print("Redirected: {}".format(buf.getvalue()))

许可

MIT许可

项目详情


下载文件

下载适用于您平台的应用程序文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码分发

此版本没有可用的源代码分发文件。有关生成分发存档的教程,请参阅此处

构建分发

stdio_proxy-0.1.3-py3-none-any.whl (6.3 kB 查看哈希值)

上传时间: Python 3

stdio_proxy-0.1.3-py2-none-any.whl (6.3 kB 查看哈希值)

上传时间: Python 2

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面