Reputation: 153
When i create a subprocess and i communicate through stdin end stdout, then the messages dont arrive unless i either flush the buffer or execute input().
So i wonder if input() flushes the buffer, and if so i want to know why.
# file1
import subprocess
import time
import select
process = subprocess.Popen(['python3', 'file2.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
read_ready, _, _ = select.select([process.stdout], [], [])
message = read_ready[0].readline().decode()
print(message)
time.sleep(11)
process.kill()
-
# file2
import sys
import time
print('1')
message = input()
# I added the sleep because the buffer gets flushed if the program stops
time.sleep(10)
If i execute this code it prints 1 immediatly. If i comment out the line with input(), then i need to wait until the file closes
Upvotes: 0
Views: 727
Reputation: 24711
Yes, the input()
function flushes the buffer. It has to, if you think about it - the purpose of the function is to present a prompt to the user and then ask for their input, and in order to make sure the user sees the prompt, the print buffer needs to be flushed.
Upvotes: 3