预先警告:我在这里出于好奇而窃窃私语。我没有具体的理由去做我在下面做的事情!在python中设置标准输出为非阻塞
下面是对Python 2.7.13
做了MacOS 10.12.5
我与蟒蛇黑客周围,我认为这会是有趣的,看看发生了什么,如果我做了stdout
非阻塞
fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
至fcntl
电话是绝对成功。然后我尝试写入大量的数据(大于OSX上管道的最大缓冲区大小 - 这是65536字节)。我以各种方式做,并得到不同的结果,有时是一个例外,有时似乎是一个严重的失败。
案例1
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 temporarily unavailable
。我觉得有道理。更高级别的文件对象包装告诉我写入调用失败。
案例2
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 temporarily unavailable
或有时不存在异常捕获,我看到下面的输出:
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
案例3
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 temporarily unavailable
或有时没有发现异常,我只看到“睡眠”。看来,通过print
ING“同床”我不从病例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)
总行了吧得到错误信息!
案例5
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还是在系统级?
这似乎是某种程度上,当写入失败导致出现错误消息时,写入过早来标准输出。该错误似乎不是一个例外。不知道它来自哪里。
N.B.我可以在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;
}
I * *想到的问题是,与非阻塞IO,调用'os.write'可以返回前写的完成,并且由于这结束了您的简单测试程序,所以'sys.stdout'也可以在写入完成之前关闭。请注意,你的C程序等待('usleep(1000)')你的Python代码没有。 – chepner
感谢您的回复。我应该发布一个更完整的Python代码片段。在写入调用之后,我有'time.sleep(1)',它没有什么区别:( –
你的操作系统是什么?你可以尝试在'strace'之类的东西下运行Python,看看系统调用了什么。 –