正文
=
open
(
err_file
,
'w'
)
def put
(
fd
)
:
print
"PUT"
fd
.
write
(
"hello, func put writen"
)
fd
.
write
(
"o"
*
4075
)
# 神奇的一行
print
"END"
if
__name__
==
'__main__'
:
p_list
=
[]
for
i
in
range
(
1
)
:
p_list
.
append
(
Process
(
target
=
put
,
args
=
(
err_fd
,)))
for
p
in
p_list
:
p
.
start
()
for
p
in
p_list
:
p
.
join
()
输出结果:
[
root
@
iZ23pynfq19Z
~
]
# py27 2.py ; cat error1.log
PUT
END
hello
,
func put
write
o
....(
有
4075
个
)
[
root
@
iZ23pynfq19Z
~
]
#
有没有觉得一种懵逼的感觉!?
如今, 心中涌现两个问题:
-
为什么第一个程序无法写入那句话 , 但是第二个却可以?
-
那个4075是什么鬼?
在解释这些问题之前, 我们需要清楚标准IO库所具有的特点: 全缓冲, 行缓冲, 不缓冲
具体可以看之前博文:https://my.oschina.net/u/2291453/blog/806102
因为现在是写入文件, 所以系统IO将采用全缓冲的方式, 也就是说, 会将缓冲区填满才刷入系统写队列.
所以上面的问题就一下子全解决了, 正因为那些 迷一般的 ‘o’,填满了整个缓冲区, 所以系统将我们的内容刷进去写队列,所以4075怎么来, 就是用4096-sizeof(“hello, func put writen”)+1, 为什么要+1, 因为缓冲区满还不行, 要大于才能触发写动作.
所以我们现在已经能够得出答案, 如果我们想要在multiprcessing.Process中, 用上面类似的方式去写文件时,有三种方法去实现:
-
写满缓冲区
-
手动调用flush()
-
将文件对象设置成不缓冲
第一第二种在上面已经阐述, 那我们简单讲下第三种:
取自
Python
官网
Document
:
open
(
name
[,