Is it safe for a subprocess opened with Popen to keep writing to a file handle after the parent python program finishes?

Viewed 42

The following code works:

test.py

import subprocess
subprocess.Popen(['bash', 'test.sh'], stdout=open("output.txt", "w"))

test.sh

sleep 10
echo "hello world"

results

[hastings@$Hastingss-Air ~/sample_project]$ python test.py
[hastings@$Hastingss-Air ~/sample_project]$ cat output.txt
[hastings@$Hastingss-Air ~/sample_project]$ cat output.txt
hello world

with the two cat calls demonstrating that yes, "hello (yawn) world" is only written after the parent has already returned control to the shell. Is this a documented feature that I can rely on?

Leaving a file handle dangling feels wrong, but the standard with open() approach definitely doesn't work since it closes the file before the subprocess is done.

0 Answers
Related