python - 在 python 中将标准输出设置为非阻塞

标签 python c posix nonblocking fcntl

事先警告:出于好奇,我正在这里闲逛。我没有特定的理由去做我在下面做的事情!

以下是在 MacOS 10.12.5 上的 Python 2.7.13 上完成的

我正在研究 python,我认为如果我让 stdout 成为非阻塞的,看看会发生什么会很有趣

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)

调用fcntl肯定是成功的。然后我尝试写入大量数据(大于 OSX 上管道的最大缓冲区大小——65536 字节)。我以多种方式进行操作并得到不同的结果,有时是异常(exception),有时似乎是一个严重的失败。

案例一

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
try:
    sys.stdout.write("A" * 65537)
except Exception as e:
    time.sleep(1)
    print "Caught: {}".format(e)

# Safety sleep to prevent quick exit
time.sleep(1)

这总是会抛出异常Caught: [Errno 35] Resource temporary unavailable。我认为有道理。更高级别的文件对象包装器告诉我写入调用失败。

案例二

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
try:
    sys.stdout.write("A" * 65537)
except Exception as e:
    print "Caught: {}".format(e)

# Safety sleep to prevent quick exit
time.sleep(1)

这有时会抛出异常 Caught: [Errno 35] Resource temporary unavailable 或者有时没有捕获到异常,我看到以下输出:

close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr

案例三

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
try:
    sys.stdout.write("A" * 65537)
except Exception as e:
    print "Caught: {}".format(e)

# Safety sleep to prevent quick exit
time.sleep(1)

print "Slept"

这有时会抛出异常 Caught: [Errno 35] Resource temporary unavailable 或者有时没有捕获到异常,我只看到“Slept”。似乎通过 printing "Slept"我没有收到案例 2 的错误消息。

案例4

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
try:
    os.write(sys.stdout.fileno(), "A" * 65537)
except Exception as e:
    print "Caught: {}".format(e)

# Safety sleep to prevent quick exit
time.sleep(1)

总是好的!

案例五

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
try:
    print os.write(sys.stdout.fileno(), "A" * 65537)
except Exception as e:
    print "Caught: {}".format(e)

# Safety sleep to prevent quick exit
time.sleep(1)

这有时没问题,有时会打印出 close failed in file object destructor 错误消息。

我的问题是,为什么在 python 中会像这样失败?我在这里做了一些根本上不好的事情 - 无论是使用 python 还是在系统级别?

似乎不知何故,当写入已经失败时,过早地写入标准输出会导致错误消息。该错误似乎并不异常(exception)。不知道它来自哪里。

注意我可以用 C 语言编写等效的程序并且它运行良好:

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <sys/fcntl.h>
#include <unistd.h>

int main(int argc, const char * argv[])
{
    const size_t NUM_CHARS = 65537;
    char buf[NUM_CHARS];

    // Set stdout non-blocking
    fcntl(fileno(stdout), F_SETFL, O_NONBLOCK);

    // Try to write a large amount of data
    memset(buf, 65, NUM_CHARS);
    size_t written = fwrite(buf, 1, NUM_CHARS, stdout);

    // Wait briefly to give stdout a chance to be read from
    usleep(1000);

    // This will be written correctly
    sprintf(buf, "\nI wrote %zd bytes\n", written);
    fwrite(buf, 1, strlen(buf), stdout);
    return 0;
}

最佳答案

这很有趣。到目前为止,我发现了一些事情:

案例一

这是因为 sys.stdout.write 将写入所有字符串或抛出异常,这不是使用 O_NONBLOCK 时所需的行为。当对 write 的底层调用返回 EAGAIN(在 OS X 上为 Errno 35)时,应该使用剩余的数据再次尝试。应改用os.write,并检查返回值以确保所有数据都已写入。

此代码按预期工作:

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)

def stdout_write(s):
    written = 0
    while written < len(s):
        try:
            written = written + os.write(sys.stdout.fileno(), s[written:])
        except OSError as e:
            pass

stdout_write("A" * 65537)

案例二

我怀疑这个错误信息是由于 https://bugs.python.org/issue11380 :

close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr

我不确定为什么有时会调用它。这可能是因为 except 语句中有一个 print 试图使用写入刚刚失败的相同 stdout

案例三

这类似于案例 1。这段代码对我来说总是有效的:

fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)

def stdout_write(s):
    written = 0
    while written < len(s):
        try:
            written = written + os.write(sys.stdout.fileno(), s[written:])
        except OSError as e:
            pass

stdout_write("A" * 65537)

time.sleep(1)

print "Slept"

案例4

确保检查 os.write 的返回值,我怀疑完整的 65537 字节没有被成功写入。

案例五

这与案例 2 类似。

关于python - 在 python 中将标准输出设置为非阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44948375/

相关文章:

python - 关于为什么 Lock 机制没有在下面的 python 脚本中实现的任何建议?

python - OpenCV Python 接口(interface)和 ctypes 库之间的互操作性

c - 缺少开发 xll 插件的 MSDN 文档?

c - 在 C 中的特定端口上运行服务守护进程?

macos - 如何在Mac OS X上列出POSIX信号量

c++ - 如何安全地删除 C++ 中的 posix 计时器?

python - Mongodb 与上一个条目的区别

Python 请求抛出 SSLError

C - `0` 使用 malloc 出现特殊字符

c - Child 和 Parent 的执行流程