Closing Files in Python

In this discussion about the easiest way to start a process and discard its output, I suggested the following code:

with open('/dev/null', 'w') as dev_null: subprocess.call(['command'], stdout=dev_null, stderr=dev_null) 

Another developer suggested this version:

 subprocess.call(['command'], stdout=open('/dev/null', 'w'), stderr=STDOUT) 

The C ++ programmer in me wants to say that when objects are released, this is an implementation detail, therefore, to avoid leaving the file descriptor for an indefinite period of time, I have to use with . But a couple of resources suggests that Python always or almost always uses reference counting for code in this case, in which case the file descriptor should be restored as soon as subprocess.call is complete, and using with not required.

(I think leaving the descriptor file open for /dev/null , in particular, hardly matters, so pretend to be an important file.)

Which approach is best?

+4
source share
3 answers

You are right, refcouting is not guaranteed. In fact, only CPython (which is the main implementation, yes, but not even remotely the only one) requires recounting. In the event that CPython ever changes this implementation detail (it is unlikely, yes, but possible), or your code ever runs in an alternative implementation, or you lose refcouting for some other reason, the file will not be closed. Therefore, given that the with statement makes cleaning very easy, I suggest that you always use the context manager when opening files.

+10
source

When the pipe to the zero device is closed, it does not matter - it will not lead to loss of data on the output or to some of them. Although you might want to use the with option always to ensure that your output files are always properly cleaned and closed, etc., This is not an example where it matters.

+1
source

The entire point of the with statement must have a controlled cleanup process. You are doing it right; do not let anyone convince you otherwise.

+1
source

Source: https://habr.com/ru/post/1342324/


All Articles