Abhishek Agarwal
Abhishek Agarwal

Reputation: 724

Closing files from subprocess stdout

Here's my code

fh = open("temp.txt", "w") 
process = subprocess.Popen(["test"], shell=True, stdout=fh)

If the process doesn't exit is it necessary to free the file handle or killing the subprocess will suffice?

Upvotes: 2

Views: 2274

Answers (1)

chris-sc
chris-sc

Reputation: 1718

Your file object was opened by your Python code and will not be closed by the subprocess. To make sure it is properly closed is your responsibility.

You could either use (not the best option):

fh = open("temp.txt", "w") 
process = subprocess.Popen(["test"], shell=True, stdout=fh)
fh.close()

or (better):

with open("temp.txt", "w") as fh:
    process = subprocess.Popen(["test"], shell=True, stdout=fh)

The latter will make sure that your file object is always closed properly, even if the subprocess command fails with some error.

Upvotes: 3

Related Questions