gpt4 book ai didi

Python: why with open file works with subprocess.Popen?(Python:为什么open file可以和subprocess.Popen一起使用?)

转载 作者:bug小助手 更新时间:2023-10-25 15:26:45 27 4
gpt4 key购买 nike



As I know, if we open a file using "with open", the file will be closed when the code reach out of the with context manager.

据我所知,如果我们使用“with open”打开一个文件,当代码到达with上下文管理器之外时,该文件将被关闭。


with open(somefile) as fd:
# do some thing
# fd.close() # automatically
print("Before We get here, the fd is closed")

So I don't understand why the code below works:

所以我不明白为什么下面的代码可以工作:


with open("hello.txt", mode="w") as fd:
p = subprocess.Popen("ping 127.0.0.1 -n 10", stdout=fd, stderr=fd)
# fd.close() # automatically
print("Before We get here, the fd is closed")

I closed the file immediately after the subprocess called, and the command ping will run for 10 seconds. Why the output of ping still can write into hello.txt successfully?
In my thought, Popen should raise exception because the fd is closed.
Any one can explain why?

在调用子进程之后,我立即关闭了该文件,命令ping将运行10秒钟。为什么ping的输出仍然可以成功写入hello.txt?在我看来,POpen应该引发异常,因为FD是关闭的。有谁能解释原因吗?


更多回答

The Popen class (see source code) creates a duplicate of the file handle. Try following get_handles and you'll find _make_inheritable

POpen类(请参阅源代码)创建文件句柄的副本。尝试按照Get_Handles进行操作,您会发现_Make_Inherable

Note that an external process can't use a Python file-like object anyway: the file-like object is only used to supply or create an OS-level file descriptor that can be used.

请注意,外部进程无论如何都不能使用类文件对象:类文件对象仅用于提供或创建可使用的操作系统级别的文件描述符。

优秀答案推荐

for the subprocess
The subprocess.Popen() is used to start a new process and interact with it.
The function returns a subprocess.Popen object, which represents the new process.

对于子流程,子流程.POpen()用于启动新流程并与其交互。该函数返回子进程.POpen对象,该对象表示新进程。


the docs are here:
https://docs.python.org/3/library/subprocess.html

文档在这里:https://docs.python.org/3/library/subprocess.html


for the file open / close.
You can check the status at each step of the code with this:

对于文件打开/关闭。您可以使用以下命令检查代码每一步的状态:


import subprocess

with open("hello.txt", mode="w") as fd:
p = subprocess.Popen("ping 127.0.0.1 -n 10", stdout=fd, stderr=fd)
print('file closed:', fd.closed)
# fd.close() # automatically
print('file closed:', fd.closed)
print("Before We get here, the fd is closed")

which gives this:

这就产生了这样的结果:


file closed: False
file closed: True
Before We get here, the fd is closed

更多回答

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