gpt4 book ai didi

python - 文件句柄为父进程打开但为每个子进程关闭

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:29 25 4
gpt4 key购买 nike

<分区>

我写了这个小例子:

import multiprocessing
from functools import partial

def foo(x, fp):
print str(x) + " "+ str(fp.closed)
return

def main():
with open("test.txt", 'r') as file:
pool = multiprocessing.Pool(multiprocessing.cpu_count())
partial_foo = partial(foo, fp=file)
print file.closed
pool.map(partial_foo, [1,2,3,4])
pool.close()
pool.join()
print file.closed
print "done"

if __name__=='__main__':
main()

将打印:

False
2 True
3 True
1 True
4 True
False
done

我的问题是为什么子进程的文件句柄关闭,我如何让它们保持打开状态以便每个进程都可以使用该文件?

因为在评论中被问到了:

$ uname -a && python2.7 -V
Linux X220 3.17.6-1-ARCH #1 SMP PREEMPT Sun Dec 7 23:43:32 UTC 2014 x86_64 GNU/Linux
Python 2.7.9

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com