#Python pop quiz:
-
#Python pop quiz:
What does the following Python3 script output in a standard Linux environment?
import subprocess
print("a")
subprocess.run(["echo", "b"])
print("c")Assume it is run as `python3 quiz.py | tr \n " "` to turn newlines into spaces.
See followup reply for solution and explanation.
-
#Python pop quiz:
What does the following Python3 script output in a standard Linux environment?
import subprocess
print("a")
subprocess.run(["echo", "b"])
print("c")Assume it is run as `python3 quiz.py | tr \n " "` to turn newlines into spaces.
See followup reply for solution and explanation.
It's `b a c`, because `print` writes into the sys.stdout *buffer* that only flushes when it goddamn feels like it, whereas `subprocess.run` plucks the file handle out of sys.stdout and hands it to the child process.
So the child process writes "b" to stdout right away, while the "a" and "c" writes happen later, at parent process shutdown.
If you instead run from a terminal *without* piping to `tr`, or you set `PYTHONUNBUFFERED=1`, then the output is instead in the `a b c` order.
yayyyyy

-
It's `b a c`, because `print` writes into the sys.stdout *buffer* that only flushes when it goddamn feels like it, whereas `subprocess.run` plucks the file handle out of sys.stdout and hands it to the child process.
So the child process writes "b" to stdout right away, while the "a" and "c" writes happen later, at parent process shutdown.
If you instead run from a terminal *without* piping to `tr`, or you set `PYTHONUNBUFFERED=1`, then the output is instead in the `a b c` order.
yayyyyy

-
@joshbuddy I definitely had one of those "am I crazy or is the world crazy" moments while debugging this.
-
R relay@relay.infosec.exchange shared this topic