This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Subprocess stdin.flush does not flush
Type: behavior Stage:
Components: None Versions: Python 3.1, Python 3.2, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: amoffat, rosslagerwall, wenjianhn
Priority: normal Keywords:

Created on 2012-02-13 09:54 by amoffat, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (3)
msg153257 - (view) Author: Andrew Moffat (amoffat) Date: 2012-02-13 09:54
The following code only works if the "p.stdin.close()" line is uncommented.  It seems that stdin only flushes to the process on stdin.close(), not on stdin.flush().

-----------------------------------

import subprocess as subp
import threading
import time


p = subp.Popen(["tr", "[:lower:]", "[:upper:]"],
    stdin=subp.PIPE, stderr=subp.PIPE, stdout=subp.PIPE, close_fds=True)


def read(stdout):
    while True:
        line = stdout.readline()
        if not line: break
        print(line.decode("utf8"))

t = threading.Thread(target=read, args=(p.stdout,))
t.daemon = True
t.start()

p.stdin.write("uppercase\n".encode())
p.stdin.flush()
#p.stdin.close()

time.sleep(1)
msg153280 - (view) Author: Ross Lagerwall (rosslagerwall) (Python committer) Date: 2012-02-13 16:40
This appears to be a buffering issue with the tr program. Replace with ["cat", "-"] and it works whether the close() is in or not.

To fix this, you need to open up the child process so that it is connected to a tty. man 4 pts if you want to investigate this further.
msg191388 - (view) Author: Jian Wen (wenjianhn) Date: 2013-06-18 07:39
The following code shows how to use pts.

#!/usr/bin/env python

import os
import pty
import shlex
import time

_args = "/usr/bin/ssh example.com"
args = shlex.split(_args)

pid, child_fd = pty.fork()

if pid == 0:
    # Child
    os.execv("/usr/bin/ssh", args)

else:
    # Parent
    while True:
        os.write(child_fd, '# keep alive\n')
        os.read(child_fd, 1024)
        
        time.sleep(2)
History
Date User Action Args
2022-04-11 14:57:26adminsetgithub: 58208
2013-06-18 07:39:48wenjianhnsetnosy: + wenjianhn
messages: + msg191388
2012-02-13 16:40:06rosslagerwallsetstatus: open -> closed

nosy: + rosslagerwall
messages: + msg153280

resolution: not a bug
2012-02-13 09:54:09amoffatcreate