4

In this discussion about the easiest way to run 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 is an implementation detail, so to avoid leaving a filehandle open for an indeterminate period of time, I should use with. But a couple of resources suggest that Python always or almost always uses reference counting for code like this, in which case the filehandle should be reclaimed as soon as subprocess.call is done and using with is unnecessary.

(I guess that leaving a filehandle open to /dev/null in particular is unlikely to matter, so pretend it's an important file.)

Which approach is best?

1
  • 3
    You should prefer the use of os.devnull over '/dev/null'. That's more important than a minor detail like the use of with in this case or not. Commented Mar 4, 2011 at 16:52

3 Answers 3

10

You are correct, refcouting is not guaranteed. In fact, only CPython (which is the main implementation, yes, but not even remotely the only one) provdies refcounting. In case CPython ever changes that implementation detail (unlikely, yes, but possible), or your code is ever run on an alternate implementation, or you lose refcouting because of any other reason, the file won't be closed. Therefore, and given that the with statement makes cleanup very easy, I would suggest you always use a context manager when you open files.

Sign up to request clarification or add additional context in comments.

1 Comment

Even CPython these days issues a ResourceWarning if you rely on __del__ to close your files. The warning is silenced by default, but it's still there.
1

When the pipe to the null device closes is irrelevant - it won't lead to data loss in the output or some such. While you maybe want to use the with variant always to ensure that your output files are always properly flushed and closed, etc., this isn't an example where this matters.

Comments

1

The entire point of the with statement is to have a controlled cleanup process. You're doing it right, don't let anyone convince you otherwise.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.