Search code examples
pythonpython-3.6python-3.2

Popen.stdout.readline() works in Python 3.2 but returns empty string in Python 3.6


I am using Popen to start a telnet process over ssh, send commands through the telnet and check the process for output to monitor the state of the telnet. The weird thing I encountered is that the code works fine with Python 3.2.3 but when I run it in Python 3.6.5 with no code changes, it fails to get the output.

I have tried

  • flushing the stdout

  • waiting up to 10s after stdout.write

  • checked stderr

def nonblockingread(sout):
   fd = output.fileno()
   fl = fcntl.fcntl(fd, fcntl.F_GETFL)
   try:
       return sout.read()
   except:
       return ""

process = Popen(shlex.split("ssh anon@server \"telnet 0 2323\""), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(nonblockingread(process.stdout)) # works for both versions
process.stdin.write(b"start service 4\n")
print(nonblockingread(process.stdout)) # works in 3.2 but not 3.6 (prints empty line)
print(process.stdout.readline()) # also prints empty line in 3.6

Solution

  • Buffering was turned on by default in 3.2.4 and 3.3.1, having been turned off inadvertently in Python 3. You need to flush your write to process.stdin for the other side to see anything.